I'm working on my first project where i am not following a book. I want to learn how to do this.
For this example, i am adding buttons and textviews to a gridlayout. To make it scroll, the layout is inside a scrollview:
Code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.sample"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="2"
android:id="@+id/list">
</GridLayout>
</ScrollView>
The buttons are added and forced to be a specific size. The textviews are set to have large text, and given layoutparams to be centered vertically. Both are added via a for loop that works on an array holding all the data:
Code:
GridLayout layout = (GridLayout) findViewById(R.id.list);
// Calculate size of buttons in dips.
int button_dip = Math.round((float) 150 * getApplicationContext().getResources().getDisplayMetrics().density);
for(int i = 0; i < list.length; i++)
{
// Create button and set its properties.
ImageButton button = new ImageButton(this);
button.setId(i);
button.setOnClickListener(this);
button.setImageResource(list[i].image_off);
// Create textview and set its properties.
TextView title = new TextView(this);
title.setText(list[i].title);
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
// The textview's layout (parameters) requires its own object.
GridLayout.LayoutParams title_layout = new GridLayout.LayoutParams();
title_layout.setGravity(Gravity.CENTER_VERTICAL);
// Add the object to the layout.
layout.addView(button, button_dip, button_dip);
layout.addView(title, title_layout);
}
This all works, except that some longer text goes off the screen instead of wrapping. The longest text does wrap, but part of the first line does go off the screen.
1 ) Is there a better way to have a scrolling GridLayout?
2) How can the text be kept on the screen, other than by adding "\n" to the text?
Related
I hope someone can help.
I have an application that I am building that currently has 3 main Layouts. All String-Arrays are in XML. First Screen Shows, Breakfast, Lunch & Dinner. Now depending on which Button is selected, Example "Lunch" a 2nd Layout comes up Showing the Lunch Menu items, such as Cheeseburger, Hamburger, Hot Dog, French Fries, Onion Rings... Let's say I select "Cheeseburger", the Item is Added to the 3rd Layout. When I click the Back button on the phone and select a new item such as "Onion Rings" that item replaces the Cheeseburger. I need it to ADD it to the List, not replace it. Can someone please tell me where my code is wrong?
Summary, I need the list to get appended with the items selected, not replaced by the selected item.
Here is my lunchActivity.java
Code:
package com.mycompany.foodmenu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class lunchActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lunchmain);
final ListView lv=(ListView)findViewById(R.id.listView1);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.lunch_menu,android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
String item=lv.getItemAtPosition(arg2).toString();
String itemordered;
itemordered = item + " added to list";
Toast.makeText(getApplicationContext(), itemordered, Toast.LENGTH_LONG).show();
// Launching new Activity on selecting List Item
Intent i = new Intent(getApplicationContext(), ListItem.class);
// sending data to new activity
i.putExtra("item", item);
startActivity(i);
}
});
}
}
Here is the lunch.xml menu file that read by the lunchActivity to create the first ListView
Code:
<resources>
<string-array name="lunch_menu">
<item>Cheeseburger</item>
<item>Hamburger</item>
<item>Bacon Cheeseburger</item>
<item>Hot Dog</item>
<item>French Fries</item>
<item>Onion Rings</item>
</string-array>
</resources>
Here is the listItem.java
Code:
package com.mycompany.foodmenu;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class listItem extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.selecteditems);
Intent i = getIntent();
ArrayList<String> myNewList = new ArrayList<String>();
String item = i.getStringExtra("item");
myNewList.add(item);
ListView selecteditems = (ListView) findViewById(R.id.listitems);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListItem.this, android.R.layout.simple_list_item_1, myNewList);
selecteditems.setAdapter(adapter);
// adapter.notifyDataSetChanged();
}
}
BTW. I have tried changing
Code:
myNewList.add(item);
to
Code:
myNewList.addAll(item);
and it just creates new problems. I have also tried adding
Code:
adapter.notifyDataSetChanged();
to the end and it makes no difference.
And here is the selectedItems.xml file that is suppose to get populated with the Selected Items from the Lunch Menu
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@drawable/main_background"
android:paddingLeft="10.0dip"
android:paddingTop="0.0dip"
android:paddingRight="10.0dip"
android:paddingBottom="10.0dip"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/listitems"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:padding="10dip"
android:textColor="#ffffff"/>
</LinearLayout>
Any help would be greatly appreciated!!
Please... Anybody got any ideas on what I am doing wrong?
StEVO_M said:
Please... Anybody got any ideas on what I am doing wrong?
Click to expand...
Click to collapse
post on stack overflow or join us on irc at #android-dev
f2prateek said:
post on stack overflow or join us on irc at #android-dev
Click to expand...
Click to collapse
I've posted on Stack Overflow and unless you get an answer within a few mins your post gets buried pretty quick.
I;ve never used irc so I'm not sure how to use it.
Sent from my Transformer Prime using Tapatalk 2
guys please help i have stucked in this problem for a long time.
Code:
public class Activity_Calculator extends StandOutWindow {
@Override
public String getAppName() {
return "test";
}
@Override
public int getAppIcon() {
return android.R.drawable.ic_menu_close_clear_cancel;
}
@Override
public void createAndAttachView(int id, FrameLayout frame) {
// create a new layout from body.xml
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View child= inflater.inflate(R.layout.activity_activity__calculator, frame, true);
WebView myWebView = (WebView)child.findViewById(R.id.webView1);
EditText field = (EditText)child.findViewById(R.id.urlField);
//myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new MyBrowser());
//myWebView.getSettings().setJavaScriptEnabled(true);
//myWebView.getSettings().setPluginsEnabled(true);
//myWebView.getSettings().setDomStorageEnabled(true);
}
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
// the window will be centered
@Override
public StandOutLayoutParams getParams(int id, Window window) {
return new StandOutLayoutParams(id, 500, 600,
StandOutLayoutParams.CENTER, StandOutLayoutParams.CENTER);
}
// move the window by dragging the view
@Override
public int getFlags(int id) {
return StandOutFlags.FLAG_DECORATION_SYSTEM
| StandOutFlags.FLAG_BODY_MOVE_ENABLE
| StandOutFlags.FLAG_WINDOW_HIDE_ENABLE
| StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TAP
| StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE
| StandOutFlags.FLAG_WINDOW_PINCH_RESIZE_ENABLE;
}
@Override
public String getPersistentNotificationMessage(int id) {
return "Click to close the SimpleWindow";
}
@Override
public Intent getPersistentNotificationIntent(int id) {
return StandOutWindow.getCloseIntent(this, Activity_Calculator.class, id);
}
}
xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=
xmlns:tools=
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Activity_Calculator" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<EditText
android:id="@+id/urlField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView1"
android:layout_centerHorizontal="true"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/urlField"
android:layout_centerHorizontal="true"
android:onClick="open"
/>
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignParentBottom="true"
android:layout_below="@+id/button1" />
</RelativeLayout>
the webview does not respond and the apps force closed, the attachment below is the logcat,guys please help
I want to use Edit text on my table row. My codes are bellow
My XML code is
XML:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#3d455b"
android:layout_alignParentLeft="true" >
<HorizontalScrollView
android:id="@+id/hscrll1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="@+id/table_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</TableLayout>
</RelativeLayout>
</HorizontalScrollView>
</ScrollView>
My Java code is
JavaScript:
public void init() {
TableLayout stk = (TableLayout) findViewById(R.id.table_main);
TableRow tbrow0 = new TableRow(this);
TextView tv0 = new TextView(this);
tv0.setText(" Actual Values ");
tv0.setTextColor(Color.WHITE);
tbrow0.addView(tv0);
TextView tv1 = new TextView(this);
tv1.setText(" Meter Reading ");
tv1.setTextColor(Color.WHITE);
tbrow0.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(" Error ");
tv2.setTextColor(Color.WHITE);
tbrow0.addView(tv2);
stk.addView(tbrow0);
for (int i = 0; i < 200; i++) {
TableRow tbrow = new TableRow(this);
TextView t1v = new TextView(this);
t1v.setText("" + i * 20);
t1v.setTextColor(Color.WHITE);
t1v.setGravity(Gravity.CENTER);
tbrow.addView(t1v);
TextView t2v = new TextView(this);
t2v.setText("" );
t2v.setTextColor(Color.WHITE);
t2v.setGravity(Gravity.CENTER);
tbrow.addView(t2v);
TextView t3v = new TextView(this);
int temp1 = Integer.parseInt(t1v.getText().toString());
int temp2 = Integer.parseInt(t2v.getText().toString());
t3v.setText(String.valueOf(temp1 - temp2));
t3v.setTextColor(Color.WHITE);
t3v.setGravity(Gravity.CENTER);
tbrow.addView(t3v);
stk.addView(tbrow);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_ascendingorder);
init();
}
}
I want to convert t2v from Textview to Edittext.
I tried Edittext t2v = new Edittext(this); But it is not working.
Can anyone guide me on how to do this?
I have an android app which turns on a sensor on my device and collects and displays data in the app to the user.
On the home screen the user presses "START" which opens a new page that displays the data.
When the user presses the back button it take them back to the home page.
The problem I am facing is when the user presses "START" again, the display page still shows values from the previous test.
Here is the AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--<uses-permission android:name="com.google.android.things.permission.USE_PERIPHERAL_IO" />
<uses-permission android:name="com.google.android.things.permission.MANAGE_INPUT_DRIVERS" />-->
<application
android:allowBackup="true"
android:icon="@drawable/company"
android:label="Company"
android:theme="@style/TempTheme" >
<activity
android:clearTaskOnLaunch="true"
android:name="MainActivity"
android:label="Company" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Part of the MainActivity code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hrbp_main);
findViewById(R.id.btn_test_temp).setOnClickListener(this);
mWrist = (TextView) findViewById(R.id.txt_wrist);
mTemp = (TextView) findViewById(R.id.txt_temp);
ClearHistory();
}
@Override
protected void onNewIntent(Intent intent) {
Log.i("DHYCO", "onNewIntent:"+intent);
super.onNewIntent(intent);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (mCurrentTag != null) {
showFragment(false, mCurrentTag);
enableSensorOrNot(false);
startFlashSensor(false);
ClearHistory();
serviceconnection.StopCount();
mFlashThread = null;
} else
super.onBackPressed();
}
private void ClearHistory() {
Tempresult = -1;
Tempcircle = (ImageView) findViewById(R.id.Tempcircle);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
ClearHistory();
enableSensorOrNot(false);
startFlashSensor(false);
serviceconnection.StopCount();
mFlashThread = null;
}
Spoiler
```java
if (type=="dialer") {
String timestamp = list.get(position).get(Constants.DATE);
holder.txtTimestamp.setVisibility(View.VISIBLE);
holder.imgDelete.setVisibility(View.GONE);
holder.txtTimestamp.setText(getDate(Long.parseLong(timestamp),"dd/MM/yyyy hh:mm:ss"));
if (Integer.parseInt(callType) == CallLog.Calls.BLOCKED_TYPE)
holder.imgCallType.setImageDrawable(context.getResources().getDrawable(R.drawable.block));
if (Integer.parseInt(callType) == CallLog.Calls.BLOCKED_TYPE)
holder.imgCallType.setImageDrawable(context.getResources().getDrawable(R.drawable.rejected));
if (Integer.parseInt(callType) == CallLog.Calls.OUTGOING_TYPE)
holder.imgCallType.setImageDrawable(context.getResources().getDrawable(R.drawable.outgoing_call));
if (Integer.parseInt(callType) == CallLog.Calls.INCOMING_TYPE)
holder.imgCallType.setImageDrawable(context.getResources().getDrawable(R.drawable.incoming_call));
if (Integer.parseInt(callType) == CallLog.Calls.MISSED_TYPE)
holder.imgCallType.setImageDrawable(context.getResources().getDrawable(R.drawable.missed_call));
if (Integer.parseInt(callType) == CallLog.Calls.ANSWERED_EXTERNALLY_TYPE)
holder.imgCallType.setImageDrawable(context.getResources().getDrawable(R.drawable.call_received));
}else if (type=="contact") {
holder.txtTimestamp.setVisibility(View.GONE);
holder.imgCallType.setVisibility(View.GONE);
holder.imgDelete.setVisibility(View.GONE);
}else if (type=="favourite"){
holder.txtTimestamp.setVisibility(View.GONE);
holder.imgCallType.setVisibility(View.GONE);
}
// listener
Bitmap finalBitmap = imgBitmap;
holder.imgPic.setOnLongClickListener(view -> {
CustomDialog imageDialog = new CustomDialog(activity,R.layout.image_dialog,"","","", finalBitmap);
imageDialog.setCancelable(true);
imageDialog.show();
return false;
});
holder.itemView.setOnLongClickListener(view->{
if (type=="dialer"){
}else if (type=="contact"){
Intent intent = new Intent(context, ContactDetailsActivity.class);
intent.putExtra("id",list.get(position).get(Constants.ID));
context.startActivity(intent);
}else if (type=="favourite"){
Intent intent = new Intent(context, FavouriteContactDetailsActivity.class);
intent.putExtra(Constants.FAVOURITE_ID,list.get(position).get(Constants.FAVOURITE_ID));
intent.putExtra(Constants.ID,list.get(position).get(Constants.ID));
ActivityOptions anim = ActivityOptions.makeSceneTransitionAnimation(activity);
context.startActivity(intent, anim.toBundle());
}
return false;
});
holder.imgDelete.setOnClickListener(v->{
SqliteFavourite sqliteFavourite = new SqliteFavourite(context.getApplicationContext());
boolean check = sqliteFavourite.deleteData("",list.get(position).get(Constants.ID));
if (check)
Snackbar.make(v,"Successfully deleted",Snackbar.LENGTH_SHORT).show();
else Snackbar.make(v,"Error occurred when deleting",Snackbar.LENGTH_SHORT).show();
});
holder.itemView.setOnClickListener(view->{
call(activity,phoneNumber);
});
```
I was using these code in an adapter.
```java
@override
public int getItemCount() {
return list.size();
}
@override
public int getItemViewType(int position) {
return position;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtContactName,txtContactNumber,txtTimestamp;
ImageView imgPic,imgCallType,imgDelete;
ConstraintLayout contactItem;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
txtContactName = itemView.findViewById(R.id.txtName);
txtContactNumber = itemView.findViewById(R.id.txtContactNumber);
txtTimestamp = itemView.findViewById(R.id.txtTimestamp);
imgPic = itemView.findViewById(R.id.imgContact);
imgCallType = itemView.findViewById(R.id.imgCallType);
contactItem = itemView.findViewById(R.id.contactItem);
imgDelete = itemView.findViewById(R.id.imgDeleteContact);
}
}
```
Whenever I am clicking on first or second item then I can hear the clickListener. But when I click on 3rd 4th or higher item then I can't hear the clickListener. Even I had set a selector there but the selector is only working for 1st and 2nd
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
androidadding="5dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/contactItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/selector"
android:clickable="true">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/imgContact"
android:layout_width="50dp"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/user_profile"
app:civ_border_color="#FF000000"
app:civ_border_width="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="SpeakableTextPresentCheck" />
<TextView
android:id="@+id/txtName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Name"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/txtContactNumber"
app:layout_constraintEnd_toStartOf="@+id/imgCallType"
app:layout_constraintStart_toEndOf="@+id/imgContact"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/txtContactNumber"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Contact Number"
app:layout_constraintBottom_toTopOf="@iD/txtTimestamp"
app:layout_constraintEnd_toStartOf="@+id/imgCallType"
app:layout_constraintStart_toEndOf="@+id/imgContact"
app:layout_constraintTop_toBottomOf="@+id/txtName" />
<TextView
android:id="@+id/txtTimestamp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="TextView"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/txtContactNumber"
app:layout_constraintStart_toEndOf="@+id/imgContact"
app:layout_constraintTop_toBottomOf="@iD/txtContactNumber" />
<ImageView
android:id="@+id/imgCallType"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/call_received"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/imgDeleteContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/selector"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@android:drawable/ic_menu_delete" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
```
When I scroll down then I can hear the listener but whenever I am on top at that layout then I can't access the listener in 3rd or more. Why it's happening? I am not getting any error in logcat. Although I can't click on some items why? I had tried to use `holder.contactItem.setOn....` but it wasn't working also.
<hr/>
When I scroll down I can listen the click. But whenever I am at top I can't listen. But I wonder I can click on Image. I meant `holder.imgPic.setOnLongClickListener.....`.
<hr/>
I have set `onTouchListener` to `itemView` but it's working. It's only not working for onCLickListener and onLongClickListener (As I said earlier it's working when I scroll down).
xxxxxx
MOD EDIT: Unnecessary link removed.