I can't set the button width inside the table view - java

I'm doing an android application where I have to dynamically put a button inside the table row. The problem is that the button that I create is stretched as in the image below:
I also put some of the application code here below so you can understand better.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_punteggio);
showAlertDialog_modality(R.layout.dialog_change_modality);
final TableLayout tableLayout = findViewById(R.id.tableLayout);
final RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
final Button btn_settings = findViewById(R.id.btn_settings);
Bundle datipassati = getIntent().getExtras();
String player = datipassati.getString("players");
giocatore = player.split("%");
Log.d("TAG", "array: " + giocatore[0]);
for (int i = 0; i < giocatore.length; i++) {
punti[i] = 0;
TableRow tbrow = new TableRow(this);
final TextView t3v = new TextView(this);
txPunti[i] = t3v;
//------------------------- Textview Player
final TextView t1v = new TextView(this);
t1v.setText(giocatore[i].toUpperCase());
t1v.setTextColor(Color.BLACK);
t1v.setGravity(Gravity.CENTER);
t1v.setTextSize(20);
t1v.setWidth(400);
tbrow.addView(t1v);
//-------------------- BTN MENO
Button btnMeno = new Button(this);
btnMeno.setText("-");
btnMeno.setTextColor(Color.BLACK);
btnMeno.setGravity(Gravity.CENTER);
tbrow.addView(btnMeno);
btnMeno.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
removepoint(t3v);
}
});
// --------------------- TEXT VIEW PUNTI
t3v.setText(punti[i]+"");
t3v.setTextSize(25);
t3v.setMaxWidth(150);
t3v.setPadding(20,0,20,0);
t3v.setTypeface(t3v.getTypeface(), Typeface.BOLD);
t3v.setTextColor(Color.RED);
t3v.setGravity(Gravity.CENTER);
tbrow.addView(t3v);
//----------------------------- BTN PIU
Button btnPiu = new Button(this);
btnPiu.setBackground(ContextCompat.getDrawable(Activity_punteggio.this, R.drawable.ic_add_circle_black_24dp));
btnPiu.setTextColor(Color.BLACK);
btnPiu.setGravity(Gravity.CENTER);
tbrow.addView(btnPiu);
btnPiu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addPoint(t3v, t1v);
}
});
tableLayout.addView(tbrow);
}
btn_settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAlertDialog_modality(R.layout.dialog_change_modality);
}
});
}
Here's also the xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity_punteggio">
<Button
android:id="#+id/btn_settings"
android:layout_width="55dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:layout_marginRight="1dp"
android:background="#android:color/transparent"
android:drawableBottom="#drawable/ic_settings_black_24dp" />
<TextView
android:id="#+id/title_player"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Chip-Chop"
android:textSize="25dp"
android:textStyle="bold|italic" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp">
</TableLayout>
</RelativeLayout>
I hope you could help me.

Please check this solution. setImageResource is the method assign
image resource. Set background method is recommended for the
background of the button.
ImageButton btnPiu = new ImageButton(this);
btnPiu.setImageDrawable(ContextCompat.getDrawable(Activity_punteggio.this, R.drawable.ic_add_circle_black_24dp));
btnPiu.setTextColor(Color.BLACK);
btnPiu.setGravity(Gravity.CENTER);
tbrow.addView(btnPiu);
btnPiu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addPoint(t3v, t1v);
}
});
tableLayout.addView(tbrow);
I used ImageButton other than Button.
setImageDrawable

try to edit android:layout_height="32dp" to android:layout_height="55dp"
android:id="#+id/btn_settings"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:layout_marginRight="1dp"
android:background="#android:color/transparent"
android:drawableBottom="#drawable/ic_settings_black_24dp" />
I hope it will work with you .

THIS is make very complex coding, Make it simpler.Don't create whole row dynamically in FOR loop. Instead of that
First Create Separate XML for that row.
Write Below code and your row append into tablelayout.
for (int i = 0; i < giocatore.length; i++) {
View trView = LayoutInflater.from(getActivity()).inflate(R.layout.xmlID,null);
TextView lblGuestName;
lblGuestName = trView.findViewById(R.id.lbl);
lblGuestName.setText("Guest 1");
tableLayout.addView(trView);
}
This Way you easily configure any complex row in tablelayout. No need to make it dynamically.
Feel free to reply.

Related

Android java code to add + and - button beside edittext

for(int i=0;i<j.size();i++)
{
TableLayout.LayoutParams tableRowParams=
new TableLayout.LayoutParams
(TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
JsonObject jb = (JsonObject) j.get(i);
String item = jb.get("item").getAsString();
String unit = jb.get("unit").getAsString();;
String price = jb.get("price").getAsString();;
TableRow tbrow1 = new TableRow(this);
TextView tv01 = new TextView(this);
tv01.setText(item);
tv01.setTextColor(Color.BLACK);
tbrow1.addView(tv01);
TextView tv11 = new TextView(this);
tv11.setText(unit);
tv11.setTextColor(Color.BLACK);
tbrow1.addView(tv11);
TextView tv21 = new TextView(this);
tv21.setText(price);
tv21.setTextColor(Color.BLACK);
tbrow1.addView(tv21);
Button button = new Button(this);
button.setText("+");
button.setTag(item);
tbrow1.addView(button);
final String id_ = (String) button.getTag();
EditText edText = new EditText(this);
edText.setInputType(InputType.TYPE_CLASS_NUMBER);
//edText.setText(0);
tbrow1.addView(edText);
Button button1 = new Button(this);
button1.setText("-");
button.setTag(item);
tbrow1.addView(button1);
final String id1_ = (String) button.getTag();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "button clicked for "+id_, Toast.LENGTH_LONG).show();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "button clicked for "+id1_, Toast.LENGTH_LONG).show();
}
})
}
I'm developing Android app for grocery shop . I'm getting itms details in json
Depending on items number I'm creating dynamic rows.
Now I want to add + and - button in each row .
I want it programmatically
How to to do it.
Example: + - button in zomato while adding food to cart .
As i click + or - button that corresponding item number should increment/decrement
You can use this library. It is a simple Android library to implement a number counter with increment and decrement buttons.
https://github.com/ashik94vc/ElegantNumberButton
try this,
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView textViewCount;
int count=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewCount=findViewById(R.id.textViewCount);
textViewCount.setText(""+count);
}
public void itemSubtractClick(View view) {
if (count>0)
textViewCount.setText(""+count--);
else
Toast.makeText(this, "not allowed", Toast.LENGTH_SHORT).show();
}
public void itemAddClick(View view) {
textViewCount.setText(""+count++);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/shape"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:onClick="itemSubtractClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon_subtract" />
<TextView
android:id="#+id/textViewCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#17F44336"
android:padding="10dp"
android:text="2"
android:textSize="18sp" />
<ImageView
android:onClick="itemAddClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon_add" />
</LinearLayout>

How to put programmatically created Horizontally Scrolling view with XML created Layout in Android?

In my app a user can select multiple images from gallery then he can view it within the app.
I have three buttons within a Relative Layout
<RelativeLayout 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="match_parent"
tools:context="com.codenemesis.multipleimg.MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="imageSelector"
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="up"
android:text="Upload"/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="viewclick"
android:text="View Images" />
To show the images I programmatically created ImageView array within HorizontalScrollView set to WRAP_CONTENT but the problem is when I click on view button HorizontalScrollView span over the whole screen like this.
I want to show HorizontalScrollView below view button. How can I do it?
Here is how I created HorizontalScrollView
HorizontalScrollView horizontalScrollView = new HorizontalScrollView(this);
LinearLayout linearLayout = new LinearLayout(this);
ViewGroup.LayoutParams prams = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayout.setLayoutParams(prams);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
horizontalScrollView.addView(linearLayout);
// mArrayUri is the arraylist of images selected from gallery
int b = mArrayUri.size();
int c = 0;
ImageView[] imageViews = new ImageView[mArrayUri.size()];
while (c < mArrayUri.size()) {
imageViews[c] = new ImageView(this);
imageViews[c].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
imageViews[c].setPadding(10,0,10,0);
imageViews[c].setImageURI(mArrayUri.get(c));
linearLayout.addView(imageViews[c]);
c++;
// Set context view
setContentView(horizontalScrollView);
The code in your xml file should be like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
tools:context="com.test.myapplication.MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="select images"
android:onClick="imageSelector"/>
<Button
android:id="#+id/button2"
android:layout_toRightOf="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="up"
android:text="Upload"/>
<Button
android:id="#+id/button3"
android:layout_toRightOf="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="viewclick"
android:text="View Images" />
<RelativeLayout
android:id="#+id/parent_panel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button"
android:layout_marginTop="10dp"
>
</RelativeLayout>
The code in you java file should be like this
public class MainActivity extends AppCompatActivity {
RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout=findViewById(R.id.parent_panel);
}
public void imageSelector(View view)
{
}
public void up(View view)
{
}
public void viewclick(View view)
{
HorizontalScrollView horizontalScrollView =
new HorizontalScrollView(this);
LinearLayout linearLayout = new LinearLayout(this);
ViewGroup.LayoutParams prams = new ViewGroup.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayout.setLayoutParams(prams);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
horizontalScrollView.addView(linearLayout);
// mArrayUri is the arraylist of images selected from gallery
int b = mArrayUri.size();
int c = 0;
ImageView[] imageViews = new ImageView[mArrayUri.size()];
while (c < mArrayUri.size()) {
imageViews[c] = new ImageView(this);
imageViews[c].setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
imageViews[c].setPadding(10, 0, 10, 0);
imageViews[c].setImageURI(mArrayUri.get(c));
linearLayout.addView(imageViews[c]);
c++;
}
relativeLayout.addView(horizontalScrollView);
}
}
This should do the trick for you.

how to set text to text view based on the selection of item in dialogfragment and value of text in main activity, is it possible?

Here I am trying to set text to a textview in my activity.
The text is set to the text view based on the text of the text view in my activity and the selected item in the custom dialog fragment.
The dialog fragment consists of recycler view and a button.when item is selected from the fragment and text of textview of my activity, and with both cases settext to the textview. I tried different code but I not getting how to achieve it anyone give me solution for it. is there a way to get it.
by using value of text and selected item, adding my math and condition to it. settext to the textview. I am beginner to coding can any one help me please I'm trying from 5 days to achieve it. please help me thanks in advance
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="YOUR DAILY TARGET"
android:layout_gravity="center"
android:id="#+id/textView7"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_gravity="center"
android:id="#+id/res"
android:layout_marginTop="20dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Select a glass"
android:layout_marginLeft="10dp"
android:id="#+id/textView6"
android:layout_gravity="center" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:src="#android:drawable/ic_input_add" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="70dp"
android:layout_height="70dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="0"
android:background="#drawable/circle"
android:gravity="center"
android:id="#+id/glasses"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="31dp"
android:layout_marginEnd="31dp"
android:layout_marginBottom="121dp" />
</RelativeLayout>
</LinearLayout>
MainActivity:
public class MainActivity extends AppCompatActivity {
private Listen selectedListen;
protected void setDataFromMyDialog(Listen listen) {
this.selectedListen = listen;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, Page.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
TextView textView = (TextView)findViewById(R.id.res);
Intent r = getIntent();
double res = r.getDoubleExtra("res", 0);
textView.setText(+res + "L"); // with this text value
double ram = Double.parseDouble(textView.getText().toString());
TextView gls = (TextView) findViewById(R.id.glasses);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DiaFragment df = new DiaFragment();
df.show(MainActivity.this.getSupportFragmentManager(), "Frag");
}
});
}
with the text of textview above and selected item in my dialog fragment by using both the values the set text of TextView glasses.is it possible to get like this
DiaFrag:
public class DiaFragment extends DialogFragment {
ListAdapter listAdapter;
public DiaFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
setCancelable(false);
Button ok = (Button) v.findViewById(R.id.submit);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.list);
listAdapter = new ListAdapter(getContext(),getData());
recyclerView.setAdapter(listAdapter);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setDataFromMyDialog(listAdapter.getSelectedData());
dismiss();
}
});
return v;
}
public static List<Listen> getData()
{
List<Listen> data = new ArrayList<>();
int[] images = {R.drawable.bottle,R.drawable.lotion,R.drawable.soap,R.drawable.soda,R.drawable.sodaa};
String[] texts = {"250ml","300ml","500ml","750ml","1ltr"};
for (int i=0;i<texts.length && i<images.length;i++){
Listen current = new Listen();
current.img = images[i];
current.text= texts[i];
data.add(current);
}
return data;
}
}

add((RelativeLayout) findViewById) to ArrayList<RelativeLayout>

I have the following code:
public class MainActivity extends Activity implements OnClickListener {
public ArrayList<RelativeLayout> buttons = new ArrayList<RelativeLayout>();
public ArrayList<Integer> drawableId = new ArrayList<Integer>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
linear = (LinearLayout) findViewById(R.id.Rlayout);
scrool = (ScrollView) findViewById(R.id.scrool);
for (int i = 0; i < buttons.size(); i++) {
{
String buttonID = "Llayout" + i;
int resID = getResources().getIdentifier(buttonID, "id",
getPackageName());
//The problem is here
buttons.get(i).add((RelativeLayout) findViewById(resID));
buttons.get(i).setOnClickListener(this);
drawableId.add(getResources().getIdentifier("supa" + i, "drawable", getPackageName()));
}
}
}
#Override
public void onClick(View v) {
for (int i = 0; i < buttons.size(); i++) {
if (buttons.get(i).getId() == v.getId()) {
index = i;
Intent trimite = new Intent(MainActivity.this, RecipeView.class);
Bundle colet = new Bundle();
colet.putString("key", Content.RETETE[i]);
colet.putInt("keyimg", drawableId.get(i));
trimite.putExtras(colet);
startActivity(trimite);
break;
}
}
}
}
I cannot get this to work:
buttons.get(i).add((RelativeLayout) findViewById(resID));
Java error says that: add((RelativeLayout) is undefined for the type RelativeLayout.
The add method works for ArrayList drawableId, one line below but not for buttons. Can someone, please, help me?
Here is my xml layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scrool"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:scrollbars="vertical"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" >
<LinearLayout
android:id="#+id/Rlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:keepScreenOn="true"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/Llayout0"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:onClick="onClick"
android:orientation="vertical" >
<ImageView
android:id="#+id/iv0"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="left"
android:contentDescription="#string/desc"
android:src="#drawable/supa0" />
<TextView
android:id="#+id/tv0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/supa"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/Llayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:onClick="onClick"
android:orientation="vertical" >
<ImageView
android:id="#+id/iv1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="left"
android:contentDescription="#string/desc"
android:src="#drawable/supa0" />
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/supa1"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
I made buttons from RelativeLayouts. Each RelativeLayout button has text and an icon next to the text. All of the RelativeLayouts buttons are in a LinearLayout so that they align under each other.
When the RelativeLayouts buttons and the ArrayList drawableId were simple arrays it worked great but I don't want to modify the array every time I add a new RelativeLayout button.
Any suggestions?
The RelativeLayout class has no add() method.
buttons is an ArrayList of RelativeLayouts. When you call buttons.get(i), you get a single RelativeLayout object. Since RelativeLayout has no add() method, you get this error.
It isn't entirely clear what your intent is with this code, but I am assuming that you are trying to add each of your RelativeLayouts to the buttons list.
If this is correct, you just need to remove the get(i) call, making that line into
buttons.add((RelativeLayout) findViewById(resID));
Try this way,hope this will help you to solve your problem.
public class MainActivity extends Activity implements View.OnClickListener {
private ArrayList<RelativeLayout> buttons = new ArrayList<RelativeLayout>();
private ArrayList<Integer> drawableId = new ArrayList<Integer>();
private LinearLayout linear;
private ScrollView scrool;
private int index;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
linear = (LinearLayout) findViewById(R.id.Rlayout);
scrool = (ScrollView) findViewById(R.id.scrool);
for (int i = 0; i < linear.getChildCount(); i++) {
{
String buttonID = "Llayout" + i;
int resID = getResources().getIdentifier(buttonID, "id",getPackageName());
buttons.add((RelativeLayout)findViewById(resID));
buttons.get(i).setOnClickListener(this);
drawableId.add(getResources().getIdentifier("supa" + i, "drawable", getPackageName()));
}
}
}
#Override
public void onClick(View v) {
for (int i = 0; i < buttons.size(); i++) {
if (buttons.get(i).getId() == v.getId()) {
index = i;
Toast.makeText(MyActivity.this,String.valueOf(index),Toast.LENGTH_SHORT).show();
Intent trimite = new Intent(MainActivity.this, RecipeView.class);
Bundle colet = new Bundle();
colet.putString("key", Content.RETETE[i]);
colet.putInt("keyimg", drawableId.get(i));
trimite.putExtras(colet);
startActivity(trimite);
break;
}
}
}
}

TextView isn't updating in Android

I'm making a simple "novelty" app that counts how many sneezes are done, it's more of a fun app that builds up experience until I do my huge project during the summer. I have two buttons, one adds a sneeze and the other clears how many sneezes there currently are. It holds the highest number of sneezes that there were previously. The problem is, the TextViews never update, they only initialize to zero. I used a Toast.makeText() to make sure that the buttons are working (they are). Any help is appreciated. Thanks
Java code:
public class MainActivity extends ActionBarActivity {
private int record_number = 0;
private int current_number = 0;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
Toast.makeText(MainActivity.this, "Button Clicked " + current_number, Toast.LENGTH_SHORT).show();
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
TextView rec_text = (TextView) findViewById(R.id.record_num);
TextView cur_text = (TextView) findViewById(R.id.current_num);
if (current_number >= record_number)
{
record_number = current_number;
}
rec_text.setText(String.valueOf(record_number));
cur_text.setText(String.valueOf(current_number));
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.michail.sneezecounter.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Sneeze Counter"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Record Number of Sneezes:"
android:id="#+id/textView"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one Sneeze"
android:id="#+id/addone"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="76dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Current Number of Sneezes"
android:id="#+id/clear"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/record_num"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Current Number of Sneezes:"
android:id="#+id/currentLabel"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/currentLabel"
android:layout_alignLeft="#+id/record_num"
android:layout_alignStart="#+id/record_num"
android:layout_marginTop="21dp"
android:id="#+id/current_num" />
</RelativeLayout>
You need to update the text of the TextViews inside the onClickListeners. In fact, all your logic for counting, clearing, and recording the record needs to be done in your onClickListeners (or methods called by them). Right now you only do it once in onCreate, then never again. You can do this in onCreate:
final TextView cur_text = (TextView) findViewById(R.id.current_num);
add_one.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
current_number += 1;
cur_text.setText(Integer.toString(current_number);
}
});
And similar for the other TextView & onClickListener.
You only set the contents of your TextViews once. You should update them every time you get a click event. Specifically:
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
{
record_number = current_number;
rec_text.setText(String.valueOf(record_number));
}
cur_text.setText(String.valueOf(current_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
}
});
NOTE: if your variables current_number, record_number, cur_text, and rec_text aren't already declared as class member variables, you'll want to do that do that so that they're accessible once you leave the scope of the method you're doing all this in (I assume it's onCreate(...).
What you are going to need to do here is update the labels during the on click events of the button. You currently only update them on activity create. This doesn't execute every time there is a click. Can I answer any questions about the fixed up version below?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView rec_text = (TextView) findViewById(R.id.record_num);
final TextView cur_text = (TextView) findViewById(R.id.current_num);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
record_number = current_number;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}

Categories