Hello fellow programmers!
In my app I want some XML listed below to be inflated OnClick. It needs to be put into another LinearLayout.I also want to change the text in the TextView and the id's of the EditTexts to "ListItem"+numOfItems. How can I do this?
XML to be inflated:
<LinearLayout
android:paddingLeft="15dp"
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<TextView
android:layout_weight="10"
android:layout_width="10dp"
android:layout_height="80dp"
android:text="1."
android:id="#+id/tvItem1"/>
<EditText
android:layout_weight="90"
android:layout_width="100px"
android:layout_height="80dp"
android:hint="List Item 1"
android:id="#+id/etItem1"
android:paddingTop="50px"/>
</LinearLayout>
Full java class:
package com.frostbytedev.randomgenie;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Steven on 6/23/13.
*/
public class Test extends Activity implements View.OnClickListener{
java.util.List<TextView> listOfET = new ArrayList<TextView>();
LinearLayout insideScroll;
ScrollView svItems;
TextView etItem1, etItem2;
Button Add, Remove;
int numOfItems = 2, width, height;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamictest);
initialize();
}
private void initialize() {
Add=(Button)findViewById(R.id.bAdd);
Remove=(Button)findViewById(R.id.bRemove);
insideScroll=(LinearLayout)findViewById(R.id.insideScroll);
etItem1=(TextView)findViewById(R.id.etItem1);
etItem2=(TextView)findViewById(R.id.etItem2);
svItems=(ScrollView)findViewById(R.id.svItems);
Add.setOnClickListener(this);
Remove.setOnClickListener(this);
listOfET.add(etItem1);
listOfET.add(etItem2);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.bAdd:
numOfItems += 1;
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setPadding(getDP(15f), 0, 0, 0);
layout.setLayoutParams(new LinearLayout.LayoutParams((getDP(80f)), LinearLayout.LayoutParams.FILL_PARENT));
TextView numberView = new TextView(this);
LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(getDP(80f),getDP(10f));
numberView.setLayoutParams(tvParams);
numberView.setText(numOfItems + ".");
layout.addView(numberView);
EditText optionText = new EditText(this);
LinearLayout.LayoutParams etParams = new LinearLayout.LayoutParams(getDP(80f),getDP(100f));
numberView.setLayoutParams(etParams);
numberView.setHint("List Option "+numOfItems);
layout.addView(optionText);
insideScroll.addView(layout);
break;
case R.id. bRemove:
listOfET.remove(numOfItems);
numOfItems -= 1;
break;
}
}
private int getDP(float i) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dp = i;
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);
return pixels;
}
}
This is my java class
Add the id´s to your XML items.....
<LinearLayout
android:paddingLeft="15dp"
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<TextView
android:id="#+id/textViewId"
android:layout_weight="10"
android:layout_width="10dp"
android:layout_height="80dp"
android:text="1."
android:id="#+id/tvItem1"/>
<EditText
android:id="#+id/editTextId"
android:layout_weight="90"
android:layout_width="100px"
android:layout_height="80dp"
android:hint="List Item 1"
android:id="#+id/etItem1"
android:paddingTop="50px"/>
</LinearLayout>
....add this code to your listView onItemClickListener....
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView <? > parent, View view,
int position, long id) {
LayoutInflater inflater = LayoutInflater.from(getBaseContext());
View theInflatedView = inflater.inflate(R.layout.your_layout, null);
//Get the textView in your xml to set the text in it
TextView textView = theInflatedView.findViewById(R.id.textViewId);
textView.setText("Text on the textView");
//Get the EditText in you xml to set the new id
EditText editText = theInflatedView.findViewById(R.id.editTextId);
editText.setId(position);
//add the view into the LinearLayout container (global variable)
insideScroll.addView(theInflatedView);
}
});
If you are clicking a button to add items to a LinearLayout then....
your activity implements OnClickListener interface....
public class MainActivity extends Activity implements OnClickListener {
setOnClickListener to your button....
button.setOnClickListener(this);
Now you receive the click on you onClick method....
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonId:
LayoutInflater inflater = LayoutInflater.from(this);
View theInflatedView = inflater.inflate(R.layout.your_layout, null);
//Get the textView in your xml to set the text in it
TextView textView = theInflatedView.findViewById(R.id.textViewId);
textView.setText("Text on the textView");
//Get the EditText in you xml to set the new id
EditText editText = theInflatedView.findViewById(R.id.editTextId);
editText.setId(linearLayout.getChildCount()+1);
//add the view into the LinearLayout (global variable)
insideScroll.addView(theInflatedView);
break;
}
}
Related
I am developing an Android application and I am facing a seemingly well-known problem (I found a lot of similar questions but no answer works for me).
I use a ListView that displays an EditText and 2 TextView by adding an item in an ArrayList each time a user presses the button enter. However when I scroll the ListView the order of the elements changes and I can not fix this problem. I understand that the problem comes from the GetView which is recharged each time and therefore, on the view each item changes position but I do not know how to adjust it.
Thanks for your help.
I have already tried to overload the getViewTypeCount () and getItemViewType functions, I also tried to remove the maximum action in the (if convertView == null) but nothing has fixed my problem.
main_game.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#android:color/black">
<ListView android:id="#+id/MyList" android:layout_height="fill_parent"
android:layout_width="fill_parent" android:descendantFocusability="beforeDescendants">
</ListView>
</LinearLayout>
activity_game.xml
<?xml version="1.0" encoding="utf-8"?>
<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: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="com.benjamin.realhacksimulatorgame.Game"
android:background="#android:color/black">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/ll_game_vertical"
android:paddingTop="0sp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/ll_game"
android:paddingTop="0sp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/user_name"
android:text="#string/name_user"
android:textColor="#android:color/holo_green_dark"
android:textSize="15sp"
android:textStyle="bold" />
<EditText
android:id="#+id/editText_game"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/holo_green_dark"
android:backgroundTint="#android:color/holo_green_dark"
android:background="#android:color/transparent"
android:textSize="15sp"
android:layout_marginLeft="10dp"
android:textCursorDrawable="#drawable/color_cursor"
android:inputType="text" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/reponse"
android:layout_below="#+id/editText_game"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/editText_game"
android:layout_alignEnd="#+id/editText_game"
android:textColor="#android:color/holo_green_dark"/>
</LinearLayout>
</RelativeLayout>
And finally the java class Game.java
package com.benjamin.realhacksimulatorgame;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Game extends Activity {
//DECLARATION
ListView myList;
private MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_game);
Intent i = getIntent();
myList = (ListView) findViewById(R.id.MyList);
myList.setItemsCanFocus(true);
myAdapter = new MyAdapter();
myList.setAdapter(myAdapter);
}
protected void FonctionTest(String test, ViewHolder holder) {
if (test.equalsIgnoreCase("ls") || test.equalsIgnoreCase("ls "))
holder.caption_text.setText("aucun fichier a affiché");
else if (test.equalsIgnoreCase("mkdir") || test.equalsIgnoreCase("mkdir "))
holder.caption_text.setText("Impossible de creer un fichie pour le moment");
else if (test.equalsIgnoreCase(""))
holder.caption_text.setText("Vous n'avez rien entré");
else if (test.equalsIgnoreCase("a "))
holder.caption_text.setText("lettre a");
else
holder.caption_text.setText("Commande inconnu\n\n\ndesole");
}
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ArrayList myItems = new ArrayList();
public MyAdapter() {
// mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListItem listItem = new ListItem();
myItems.add(listItem);
notifyDataSetChanged();
}
//GET SIZE LIST
public int getCount() {
return myItems.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// if (convertView == null || ((ViewHolder)convertView.getTag()).id != holder.caption_edit.getId()) {
if (convertView == null ) {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.activity_game, null);
holder = new ViewHolder();
holder.caption_edit = (EditText) convertView.findViewById(R.id.editText_game);
holder.caption_text = (TextView) convertView.findViewById(R.id.reponse);
holder.caption_name = (TextView) convertView.findViewById(R.id.user_name);
//holder.id = holder.caption_edit.getId();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.caption_edit.setId(position);
//we need to update adapter once we finish with editing
final ViewHolder finalHolder = holder;
holder.caption_edit.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
//FILTER
if (event.getAction()!=KeyEvent.ACTION_DOWN) {
Toast.makeText(Game.this, "le retrun true prend effet" , Toast.LENGTH_LONG).show();
return true;
}
//IF USER CLICK ON ENTER BUTTON
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
//DISABLED OLD EDITTEXT
finalHolder.caption_edit.setEnabled(false);
FonctionTest(finalHolder.caption_edit.getText().toString(), finalHolder);
//NEXT ITEM
final int position = v.getId();
final EditText Caption = (EditText) v;
final TextView Caption_text = (TextView) v;
final TextView Caption_name = (TextView) v;
((ListItem) myItems.get(position)).caption_edit = Caption.getText().toString();
((ListItem) myItems.get(position)).caption_text = Caption.getText().toString();
((ListItem) myItems.get(position)).caption_name = Caption.getText().toString();
//Toast.makeText(Game.this, "Ceci est l'editeur numero " + position, Toast.LENGTH_LONG).show();
//CREATE NEW ITEM
ListItem listItem = new ListItem();
myItems.add(listItem);
}
return true;
}
});
return convertView;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
class ViewHolder {
int id;
EditText caption_edit;
TextView caption_text;
TextView caption_name;
}
class ListItem {
int id;
String caption_edit;
String caption_text;
String caption_name;
}
}
I am just starting with android, so I don't have much to show of what I have so far...
I am trying to make a to-do list. I have seen tutorials on how to do this with a menu for input and have the tasks displayed in a ListView, however I would like the user to input the task into an EditText instead. I was using this (which doesn't use a ListView) to just have a button click make a new TextView underneath the EditText, however I couldn't add buttons next to the TextView which would remove it (when the user finishes a task).
Using a ListView seems much easier for this, but how can I have the EditText input go to a ListView with all the tasks and buttons to remove them (permanently, not just set visibility to 0)? I would also like the tasks to be stored, so the user can close the app and return with the tasks still there.
Any ideas? I haven't made much progress.
I recommend you to use RecyclerView instead of Listview. compile this in your Gradle
compile 'com.levelupstudio:expandable-recyclerview:1.0.1'
Here is the mainActivity.java
public class MainActivity extends ActionBarActivity implements
RecyclerViewAdapter.OnItemClickListener{
private RecyclerView myRecyclerView;
private LinearLayoutManager linearLayoutManager;
private RecyclerViewAdapter myRecyclerViewAdapter;
EditText nameField;
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myRecyclerView = (RecyclerView)findViewById(R.id.myrecyclerview);
linearLayoutManager =
new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
/*
linearLayoutManager =
new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
*/
myRecyclerViewAdapter = new RecyclerViewAdapter(this);
myRecyclerViewAdapter.setOnItemClickListener(this);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
nameField = (EditText)findViewById(R.id.namefield);
btnAdd = (Button)findViewById(R.id.addbutton);
btnAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String newName = nameField.getText().toString();
Context context= getApplicationContext();
myRecyclerViewAdapter.add(0,newName);
Toast.makeText(context,"You added" +newName.toUpperCase()+ "in your view",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onItemClick(RecyclerViewAdapter.ItemHolder item, int position) {
Toast.makeText(this,
"Remove " + position + " : " + item.getItemName(),
Toast.LENGTH_SHORT).show();
}}
And AdapterClass for Recycler
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ItemHolder> {
private List<String> itemsName;
private OnItemClickListener onItemClickListener;
private LayoutInflater layoutInflater;
public RecyclerViewAdapter(Context context){
layoutInflater = LayoutInflater.from(context);
itemsName = new ArrayList<String>();
}
#Override
public RecyclerViewAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.list_item, parent, false);
return new ItemHolder(itemView, this);
}
#Override
public void onBindViewHolder(RecyclerViewAdapter.ItemHolder holder, int position) {
holder.setItemName(itemsName.get(position));
}
#Override
public int getItemCount() {
return itemsName.size();
}
public void setOnItemClickListener(OnItemClickListener listener){
onItemClickListener = listener;
}
public OnItemClickListener getOnItemClickListener(){
return onItemClickListener;
}
public interface OnItemClickListener{
public void onItemClick(ItemHolder item, int position);
}
public void add(int location, String iName){
itemsName.add(location, iName);
notifyItemInserted(location);
}
public static class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private RecyclerViewAdapter parent;
TextView textItemName;
public ItemHolder(View itemView, RecyclerViewAdapter parent) {
super(itemView);
itemView.setOnClickListener(this);
this.parent = parent;
textItemName = (TextView) itemView.findViewById(R.id.item_name);
}
public void setItemName(CharSequence name){
textItemName.setText(name);
}
public CharSequence getItemName(){
return textItemName.getText();
}
#Override
public void onClick(View v) {
final OnItemClickListener listener = parent.getOnItemClickListener();
if(listener != null){
listener.onItemClick(this, getPosition());
}
}
}}
and your xml file
<LinearLayout 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=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/namefield"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/addbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/myrecyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
list_xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="16dp"
android:background="#android:color/holo_blue_light"
android:orientation="vertical">
<TextView
android:id="#+id/item_name"
android:layout_centerVertical="true"
android:layout_margin="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
I am having some trouble with my button listener in my listView. I have my custom adapter which is printing out my row (TextView..Button..Edittext..Button), Within this class I have set up my Listeners. What I am trying to do is when either one of the buttons is clicked they will increment or decrement the editText in the row. The trouble that I am having though is the onClickListener() and getLayoutInflater() are both coming up red. How do I fix this and is my code correct for what I am trying to do? Thanks
My custom adapter class
package com.example.rory.dbtest;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.pinchtapzoom.R;
public abstract class CustomCursorAdapter extends CursorAdapter implements View.OnClickListener {
public int counter = 0;
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.item1);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0))));
}
public View getView(final int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = (LinearLayout)inflater.inflate(R.layout.row, null);
}
final EditText edit1 = (EditText)convertView.findViewById(R.id.runningTotal);
Button plusButton = (Button) convertView.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new onClickListener()
{
public void onClick(View v)
{
counter++;
edit1.setText(Integer.toString(counter));
}
});
//final EditText edit1 = (EditText)convertView.findViewById(R.id.runningTotal);
Button minusButton = (Button) convertView.findViewById(R.id.minusButton);
plusButton.setOnClickListener(new onClickListener()
{
public void onClick(View v)
{
counter--;
edit1.setText(Integer.toString(counter));
}
});
return convertView;
}
}
And if it is needed my XML file for each row
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="#+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:paddingBottom="5dp"
android:hint="#string/hint"/>
<Button
android:id="#+id/plusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/plusButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/runningTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hint"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/minusButton"
android:layout_toStartOf="#+id/minusButton"
android:layout_marginRight="30dp" />
<Button
android:id="#+id/minusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/minusButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Instead of getLayoutInflater() use
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
you can get the context from the constructor:
Context context;
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
this.context = context;
}
And instead of onClickListener use View.onClickListener
You can remove the implements View.OnClickListener as well, you're not using it anyway.
I want to fix a button on top of the layout and just below the button a dynamic edit text is created. I am creating my own Adapter. On button click another activity starts and returns string which is to be shown on the list view items below the button. How can I do this ?
My XML Layout -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<EditText
android:id="#+id/etList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
</LinearLayout>
My list view adapter -
package com.example.tasktable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class TaskAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
Button click;
TextView textView;
public TaskAdapter(Context context, String[] values) {
super(context, R.layout.list_view, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflator.inflate(R.layout.list_view, parent, false);
click = (Button) rowView.findViewById(R.id.button1);
textView = (TextView) rowView.findViewById(R.id.etList);
textView.setText(values[position]);
return rowView;
}
}
I don't want to inflate button with every edit text.
You can position layout elements with Relative Layouts https://developer.android.com/reference/android/widget/RelativeLayout.html
//try this way, hope this will help you...
**XML** code
**activity.xml**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/lnrEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</LinearLayout>
**list_activity.xml**
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
**list_item.xml**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="#+id/txtValue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/btnSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select"/>
</LinearLayout>
**ACTIVITY** code
**MyActivity**
public class MyActivity extends Activity{
private Button btnAdd;
private LinearLayout lnrEdit;
private final int GET_LIST_ITEM = 1;
private HashMap<String,String> listItemMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
btnAdd = (Button) findViewById(R.id.btnAdd);
lnrEdit = (LinearLayout) findViewById(R.id.lnrEdit);
listItemMap = new HashMap<String, String>();
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this,MyListActivty.class);
startActivityForResult(intent,GET_LIST_ITEM);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == GET_LIST_ITEM);
{
String getListValue = data.getStringExtra("value");
int index = data.getIntExtra("index",0);
if(listItemMap.containsKey(String.valueOf(index))){
Toast.makeText(this,"This item already taken !!!",Toast.LENGTH_LONG).show();
} else{
listItemMap.put(String.valueOf(index),getListValue);
EditText editText = new EditText(this);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setId(index);
editText.setText(getListValue);
editText.setTag(getListValue);
editText.setFocusable(false);
editText.setFocusableInTouchMode(false);
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value = v.getTag().toString();
Toast.makeText(MyActivity.this,value,Toast.LENGTH_SHORT).show();
}
});
lnrEdit.addView(editText);
}
}
}
}
}
**MyListActivity**
public class MyListActivty extends ListActivity{
private String[] listArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
listArray = new String[]{"Android4.1","Android4.2","Android4.3","Android4.4","Android4.5"};
setListAdapter(new TaskAdapter(this,listArray));
}
class TaskAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public TaskAdapter(Context context, String[] values) {
super(context, R.layout.list_item, values);
this.context = context;
this.values = values;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
holder.button = (Button) convertView.findViewById(R.id.btnSelect);
holder.textView = (TextView) convertView.findViewById(R.id.txtValue);
convertView.setTag(holder);
} else{
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(values[position]);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("index",position);
intent.putExtra("value",values[position]);
setResult(RESULT_OK,intent);
finish();
}
});
return convertView;
}
#Override
public int getCount() {
return values.length;
}
}
static class ViewHolder{
Button button;
TextView textView;
}
}
I am simply using LayoutInflater to get A View(Button) From a layout.xml file other then the activity_main.xml. but When I change the setText("") property of the button the button property does not updates.
I am checking if I can change the text property of the button element in the testlayout.xml But when I set the property of the Button in onCreate and when I check for that property in call that was not changed...
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = (LayoutInflater)this.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.testlayout, null);
Button btn = (Button)linearLayout.findViewById(R.id.testbtn);
btn.setText("Hello");
}
public void call(View v){
Button btn = (Button)findViewById(R.id.testBtn);
Toast.makeText(this, btn.getText(), Toast.LENGTH_SHORT).show();
}
Activity_main.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"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/mainBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="73dp"
android:text="Button"
android:onClick="call"
/>
</RelativeLayout>
testlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/testBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
You need to add this linearlayout to your activity:
LayoutInflater inflater = (LayoutInflater)this.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.testlayout, null);
Button btn = (Button)linearLayout.findViewById(R.id.button1);
btn.setText("Hello");
RelativeLayout rl=findViewById(R.id.root);
rl.addView(linearLayout);
You need to add testlayout.xml as a child to the activity view using ViewGroup.addView(View child) method. Currently you see the button from the first layout. What are you trying to do ?
You need to add the other xml to your current view :-
package com.example.testdynamicviews;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout main = (LinearLayout)findViewById(R.id.mainView); // Your custom view will be added in this layout
TextView text = myView();
text.setText("Rahul GuptaRahul GuptaRahul GuptaRahul GuptaRahul GuptaRahul GuptaRahul Gupta");
main.addView(text); // You forgot to add this line
Button button = myCustomButton();
button.setText("Custom Button");
main.addView(button);
}
public TextView myView(){
View v;
LayoutInflater li = LayoutInflater.from(getBaseContext());
v = li.inflate(R.layout.textview, null);
int width = (int) (getResources().getDimension(R.dimen.testwidth)/ getResources().getDisplayMetrics().density);
v.setLayoutParams(new LinearLayout.LayoutParams(width,LinearLayout.LayoutParams.WRAP_CONTENT));
return (TextView) v;
}
public Button myCustomButton(){
View v;
LayoutInflater li = LayoutInflater.from(getBaseContext());
v = li.inflate(R.layout.custombutton, null);
v.setBackgroundColor(Color.RED);
int width = (int) (getResources().getDimension(R.dimen.testwidth)/ getResources().getDisplayMetrics().density);
LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 10, 0, 0);
v.setLayoutParams(params);
return (Button) v;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
textview.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="sgfiughbjkh"
android:singleLine="true"
android:textSize="#dimen/testsize"
android:background="#android:color/holo_blue_bright"
android:ellipsize="end" >
</TextView>
custombutton.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/holo_blue_bright"
android:text="sgfiughbjkh"
android:textSize="#dimen/testsize" />