I am adding dynamic row with textview in table layout, Also I want x y coordinates of that textview. For that I used view.getLocationOnScreen(loc) method.
But is showing only last item coordinates, I want to show all item coordinates.
This is my source code please help me for that.
Thanks you.
public class MainActivity extends Activity {
TextView tv1, tv2;
TableRow row;
TextView txt;
TableLayout tl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tl = (TableLayout) findViewById(R.id.tableLayout1);
for (int i = 0; i <= 15; i++) {
row = new TableRow(this);
txt = new TextView(this);
tl.addView(row);
row.addView(txt);
readLocation();
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
readLocation();
}
private void readLocation() {
int[] locationOnScreen = new int[2];
txt.getLocationOnScreen(locationOnScreen);
txt.setText(locationOnScreen[0] + " : " + locationOnScreen[1]);
}
}
and my following xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TableLayout>
</ScrollView>
You shouldn't try to get those coordinates in onCreate method in this way since layout procedures are not yet completed at this point.
Here is a little bit modified demo base on your code:
public class MainActivity extends Activity {
ArrayList<TextView> txt = new ArrayList<TextView>();
TableLayout tl;
Handler _h = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tl = (TableLayout) findViewById(R.id.tableLayout1);
for (Integer i = 0; i <= 15; i++) {
TableRow therow = new TableRow(this);
TextView thetxt = new TextView(this);
therow.addView(thetxt);
tl.addView(therow);
txt.add(thetxt);
thetxt.setText("stub");
}
tl.requestLayout();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
_h.postDelayed(new Runnable() {
#Override
public void run() {
for (Integer i = 0; i <= 15; i++) {
TextView thetxt = txt.get(i);
int[] locationOnScreen = new int[2];
thetxt.getLocationOnScreen(locationOnScreen);
thetxt.setText(locationOnScreen[0] + " : " + locationOnScreen[1]);
}
}
}, 1000);
}
}
The key point is postDelayed in onResume that lets the system to position all views correctly.
Related
"I want to create a quiz section inside fragment tab and the structure should be as below
Question1
RadioGroup1
RadioButton1
RadioButton2
RadioButton3
RadioButton4
Question2
RadioGroup2
RadioButton5
RadioButton6
RadioButton7
RadioButton8
Question3
RadioGroup3
RadioButton9
RadioButton10
RadioButton11
RadioButton12
With the below code i could able to create just one question and one radio button, i want to make it dynamic in the future
private void creatRadioButtons() {
group = new RadioGroup(this.getContext());
// group = (RadioGroup) view.findViewById(R.id.radioGroup);
int[] panels = getResources().getIntArray(R.array.no_of_solar_panels);
int no_of_que = 2;
for(int i = 0; i < no_of_que; i++){
// textView = (TextView) view.findViewById(R.id.question);
textView = new TextView(this.getContext());
textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
textView.setText("Question number " + i);
linearLayout.addView(textView);
for (int j = 0; j< panels.length; j++){
button = new RadioButton(this.getContext());
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
button.setText(String.valueOf(panels[j]));
group.setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT));
group.addView(button);
}
linearLayout.addView(group);
}
}
"
This is how my screen is coming up now
Please try this code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="#+id/parentLayout"/>
</ScrollView>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private LinearLayout parentLayout;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=MainActivity.this;
parentLayout=findViewById(R.id.parentLayout);
createRadioButtons();
}
private void createRadioButtons(){
//Number pf questions
int[] panels = new int[]{1,2,3,4,5};
int no_of_que = 20;
TextView question;
RadioGroup radioGroup;
RadioButton radioButton;
for (int i=0;i<no_of_que;i++){
question = new TextView(context);
question.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
question.setText("Question: "+i);
parentLayout.addView(question);
radioGroup=new RadioGroup(context);
radioGroup.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
parentLayout.addView(radioGroup);
for(int j=0;j<panels.length;j++){
radioButton=new RadioButton(context);
radioButton.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));;
radioButton.setText("Radio Button");
radioGroup.addView(radioButton);
}
}
}
}
Try This I Already Did Quiz Kind Of Application With Question Type Fill In The Blank, Match The Following, Check Box, Radio Button
This is activity_main.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:orientation="vertical"
android:id="#+id/rel_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:id="#+id/questionsLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</RelativeLayout>
This is my QuestionChoiceVo.java (This class to hold question and it's choices)
import java.io.Serializable;
import java.util.ArrayList;
public class QuestionChoiceVo implements Serializable {
String question;
ArrayList<String> choiceArrayList;
public QuestionChoiceVo(String question, ArrayList<String> choiceArrayList)
{
this.question = question;
this.choiceArrayList = choiceArrayList;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public ArrayList<String> getChoiceArrayList() {
return choiceArrayList;
}
public void setChoiceArrayList(ArrayList<String> choiceArrayList) {
this.choiceArrayList = choiceArrayList;
}
}
This is my MainActivity class.
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialiseView();
}
private void initialiseView() {
linearLayout = (LinearLayout) findViewById(R.id.questionsLinearLayout);
ArrayList<QuestionChoiceVo> questionChoiceVoArrayList = new ArrayList<>();
QuestionChoiceVo mQuestionChoiceVoOne = new QuestionChoiceVo("Question One", new ArrayList<String>() {{add("Choice One");add("Choice Two");add("Choice Three");}});
QuestionChoiceVo mQuestionChoiceVoTwo = new QuestionChoiceVo("Question Two", new ArrayList<String>() {{add("Choice One");add("Choice Two");add("Choice Three");}});
QuestionChoiceVo mQuestionChoiceVoThree = new QuestionChoiceVo("Question Three", new ArrayList<String>() {{add("Choice One");add("Choice Two");add("Choice Three");}});
questionChoiceVoArrayList.add(mQuestionChoiceVoOne);
questionChoiceVoArrayList.add(mQuestionChoiceVoTwo);
questionChoiceVoArrayList.add(mQuestionChoiceVoThree);
prepareQuestionAnswerLayout(questionChoiceVoArrayList);
}
private void prepareQuestionAnswerLayout(ArrayList<QuestionChoiceVo> questionChoiceVoArrayList) {
for (QuestionChoiceVo mQuestionChoiceVo : questionChoiceVoArrayList) {
LinearLayout mSingleQuestionLinearLayout = new LinearLayout(this);
mSingleQuestionLinearLayout.setOrientation(LinearLayout.VERTICAL);
mSingleQuestionLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TextView mTextView = new TextView(this);
mTextView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mTextView.setText(mQuestionChoiceVo.getQuestion());
mTextView.setTextSize(20f);
mSingleQuestionLinearLayout.addView(mTextView);
RadioGroup mChoiceRadioGroup = setUpChoices(mQuestionChoiceVo);
RelativeLayout.LayoutParams radioGroupLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mChoiceRadioGroup.setLayoutParams(radioGroupLayoutParams);
mSingleQuestionLinearLayout.addView(mChoiceRadioGroup);
linearLayout.addView(mSingleQuestionLinearLayout);
}
}
private RadioGroup setUpChoices(QuestionChoiceVo mQuestionChoiceVo) {
RadioGroup radioGroup = new RadioGroup(this);
radioGroup.setId(View.generateViewId());
for (int i = 0; i < mQuestionChoiceVo.getChoiceArrayList().size(); i++){
RadioButton radioButton = new RadioButton(this);
radioButton.setText(mQuestionChoiceVo.getChoiceArrayList().get(i));
radioButton.setTextSize(18f);
RadioGroup.LayoutParams radioGroupLayoutParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
radioGroupLayoutParams.setMargins(10, 10, 10, 10);
radioButton.setPadding(10, 10, 10, 10);
radioButton.setLayoutParams(radioGroupLayoutParams);
radioButton.setId(View.generateViewId());
radioGroup.addView(radioButton);
}
return radioGroup;
}
}
Output As Your Requirement :
You should use RecyclerView instead of just adding fix number of question at design time,via RecyclerView you can add as much as question you want dynamically.
You need to use recyclerview to create dynamic no. of questions. In recycler layout, create a question with four radio buttons.
For recycler example, see this
I'm new in Android.
I need to draw custom view (or close if it exists) on search button click.
Now I implemented it this way:
public class CategoryActivity extends AppCompatActivity {
private FrameLayout relativeLayout;
private Toolbar myToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
relativeLayout = (FrameLayout) findViewById(R.id.activity_demo);
myToolbar = (Toolbar) findViewById(R.id.demo_toolbar);
myToolbar.setTitle(R.string.main_page);
setSupportActionBar(myToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.demo_activity_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
MyView myView = new MyView(this); //create vustom view
int cX = relativeLayout.getWidth() / 2; //calculate coordinates
int cY = relativeLayout.getHeight() / 2;
FrameLayout frameLayout = new FrameLayout(this); //create new layout
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(cX, cY);
layoutParams.setMargins(relativeLayout.getWidth() - timerX, relativeLayout.getPaddingTop() + myToolbar.getHeight(), 0, 0);
frameLayout.setLayoutParams(layoutParams);
frameLayout.addView(myView);
relativeLayout.addView(frameLayout);
return super.onOptionsItemSelected(item);
...
}
}
It should look like this
What is right way to do it?
Thanks.
I did not understand your problem completely because you have not given error log or shown problem you are getting.
I have made a simplest example to show How to add view dynamically. Check this example, after that you can ask question for your scenario.
layout : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btn_add_view"
android:text="Add new view dynamically"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Code : MainActivity.java
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
private Button btnAddView;
int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
btnAddView = (Button) findViewById(R.id.btn_add_view);
btnAddView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView tv = new TextView(MainActivity.this);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
tv.setText("sample text" + count++);
linearLayout.addView(tv);
}
});
}
}
Output :
I am trying to add toggle buttons dynamically in a linear layout. I have successfully done this- 2 rows with each row having 2 buttons.
Below is the code for it::
public class MainActivity extends Activity
{
LinearLayout VertLayout;
LayoutInflater inflater;
LinearLayout lnrLay_forXaxis;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
make_seat();
}
private void initialize()
{
VertLayout = (LinearLayout) findViewById(R.id.lnrLyMain);
inflater = (LayoutInflater) this.getLayoutInflater();
}
private void make_seat()
{
try{
for(int y=0;y<2;y++)
{
lnrLay_forXaxis = new LinearLayout(this);
lnrLay_forXaxis.setBackgroundColor(Color.CYAN);
lnrLay_forXaxis.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
lnrLay_forXaxis.setLayoutParams(LLParams);
for(int x=0;x<2;x++)
{
final View sngl_lnrLay = (View) inflater.inflate(R.layout.lnrly_btn, null);
final ToggleButton btt = (ToggleButton) sngl_lnrLay.findViewById(R.id.ToggleButton01);
btt.setChecked(false);
btt.setText("btn-"+x+y);
btt.setTextOn("btn-"+ x+y+" -ON");
btt.setTextOff("btn-"+x+y);
lnrLay_forXaxis.addView(sngl_lnrLay);
}
VertLayout.addView(lnrLay_forXaxis);
}
}
catch(Exception ex)
{Log.d("exp",ex.toString());}
}
}
in activity_main.xml:
<LinearLayout
android:id="#+id/lnrLyMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCFFCC"
android:orientation="vertical" >
</LinearLayout>
in lnrly_btn.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ToggleButton
android:background="#drawable/btn_toggle_bg"
style="#style/YourThemeName"
android:checked="true"
android:id="#+id/ToggleButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp">
</ToggleButton>
</LinearLayout>
Now i want to add some data with each toggle button(think it should be tag i should be using) and add another button to the activity(lets say button-x). So, after selecting few toggle buttons and then clicking on button-x; a toast/Log will appear showing the selected toggle buttons added/tagged values.
How can i do this.
You can do something like that:
Add field to your Activity:
ArrayList<View> toggles = new ArrayList<>();
Then:
for(int y=0;y<2;y++)
{
lnrLay_forXaxis = new LinearLayout(this);
lnrLay_forXaxis.setBackgroundColor(Color.CYAN);
lnrLay_forXaxis.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
lnrLay_forXaxis.setLayoutParams(LLParams);
for(int x=0;x<2;x++)
{
final View sngl_lnrLay = (View) inflater.inflate(R.layout.lnrly_btn, null);
final ToggleButton btt = (ToggleButton) sngl_lnrLay.findViewById(R.id.ToggleButton01);
Object tag; //your object,int, string ,whatever
//init your tag
btt.setTag(tag);
btt.setChecked(false);
btt.setText("btn-" + x + y);
btt.setTextOn("btn-" + x + y + " -ON");
btt.setTextOff("btn-" + x + y);
toggles.add(btt);
lnrLay_forXaxis.addView(sngl_lnrLay);
}
VertLayout.addView(lnrLay_forXaxis);
}
Button add = new Button(this);
LayoutParams btParams = new LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
btParams.gravity = Gravity.CENTER;
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (View toggle: toggles)
Log.d("TAG", toggle.getTag().toString());
}
});
VertLayout.addView(add, btParams);
My problem is the Scroll in a Horizontal ScrollView automatically moves to the right of the screen(End of the column) when typing in a EditText. The problem with this is I can not see what I'm typing in a edit text.
Here's my 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:tag="dasd"
android:id="#+id/linearlayout1">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:id="#+id/horizontalScrollView" >
<TableLayout android:id="#+id/table_grades" android:layout_height="wrap_content" android:layout_width="wrap_content" >
</TableLayout>
</HorizontalScrollView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:layout_gravity="center"
android:id="#+id/btnGet" />
</LinearLayout>
</LinearLayout>
And my Code:
public class MainActivity extends ActionBarActivity {
List<String> activity = new ArrayList<String>(Arrays.asList("Long exam 1", "Long exam 2", "Long exam 3", "asdasddadsasd", "asdasdasdas", "dasdsasdasds", "dasdsasdasds", "dasdsasdasds"));
List<String> students = new ArrayList<String>(Arrays.asList("asd", "dd", "dd"));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TableLayout table_grades = (TableLayout) findViewById(R.id.table_grades);
final HorizontalScrollView s = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
TableRow trHeader = new TableRow(this);
TableRow.LayoutParams llp = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT);
trHeader.setLayoutParams(llp);
TextView studentName = new TextView(this);
studentName.setBackgroundResource(R.drawable.cell_shape_header_studentname);
studentName.setPadding(0, 5, 0, 0);
studentName.setText("Student Name");
studentName.setTextColor(Color.parseColor("#FFFFFFFF"));
studentName.setTypeface(null, Typeface.BOLD);
TextView[] headers = new TextView[activity.size()];
for (int i = 0; i < activity.size(); i++) {
headers[i] = new TextView(this);
headers[i].setBackgroundResource(R.drawable.cell_shape_header_activities);
headers[i].setPadding(0, 5, 0, 0);
headers[i].setText(activity.get(i).toString());
headers[i].setTextColor(Color.parseColor("#FFFFFFFF"));
headers[i].setTypeface(null, Typeface.BOLD);
}
trHeader.addView(studentName);
for (int i = 0; i < headers.length; i++) {
trHeader.addView(headers[i]);
}
table_grades.addView(trHeader);
TableRow[] studentRow = new TableRow[students.size()];
TextView[] studentRecord;
for (int i = 0; i < students.size(); i++) {
studentRow[i] = new TableRow(this);
studentRow[i].setLayoutParams(llp);
studentRecord = new TextView[students.size()];
studentRecord[i] = new TextView(this);
studentRecord[i].setBackgroundResource(R.drawable.cell_shape);
studentRecord[i].setPadding(0, 5, 0, 0);
studentRecord[i].setLayoutParams(llp);
studentRecord[i].setText(students.get(i).toString());
studentRecord[i].setTextColor(Color.parseColor("#FFFFFFFF"));
studentRow[i].addView(studentRecord[i]);
}
EditText ed;
final List<EditText> studentEditTexts = new ArrayList<EditText>();
for (int i = 0; i < studentRow.length; i++) {
for (int j = 0; j < activity.size(); j++) {
ed = new EditText(this);
studentEditTexts.add(ed);
ed.setBackgroundResource(R.drawable.cell_shape_edittexts);
ed.setLayoutParams(llp);
ed.setTypeface(null, Typeface.BOLD);
ed.setGravity(Gravity.CENTER);
ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
ed.setInputType(InputType.TYPE_CLASS_NUMBER);
ed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s.fullScroll(HorizontalScrollView.FOCUS_LEFT);
}
});
studentRow[i].addView(ed);
}
}
for (int i = 0; i < studentRow.length; i++) {
table_grades.addView(studentRow[i]);
}
Button bt = (Button) findViewById(R.id.btnGet);
final String[] strings = new String[studentEditTexts.size()];
for (int i = 0; i < studentEditTexts.size(); i++) {
strings[i] = studentEditTexts.get(i).getText().toString();
}
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Get inputs
for (int i = 0; i < studentEditTexts.size(); i++) {
strings[i] = studentEditTexts.get(i).getText().toString();
Toast.makeText(MainActivity.this, strings[i] + " text length is: " + strings[i].length(), Toast.LENGTH_SHORT).show();
}
*/
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am creating an list view with dynamically added checkboxes.
However i want to add a onClickListener to it so when i change the state of a certain checkbox, i do something.
However i cannot seem to find out how to create Uniqe ID's from an array.
this is my code:
public class SingleContactActivity extends Activity implements
OnCheckedChangeListener {
private int Array_Count = 0;
private String url = "http://www.EXAMPLE.com";
private JSONArray items = null;
private String product;
private String id;
private String store;
private String state;
private String uniqeID;
ArrayList<HashMap<String, String>> listitems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
listitems = new ArrayList<HashMap<String, String>>();
// getting intent data
// Get JSON values from previous intent
new downloadJsonitems().execute();
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
}
private class downloadJsonitems extends AsyncTask<Void, Void, Void> {
LinearLayout my_layout = (LinearLayout) findViewById(R.id.test);
LinearLayout my_checked_layout = (LinearLayout) findViewById(R.id.checked);
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
url = url + "1";
Log.i("pref", "url =" + url);
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
JSONObject jsonObj;
try {
jsonObj = new JSONObject(jsonStr);
Log.i("pref", "json =" + jsonObj);
items = jsonObj.getJSONArray("items");
for (int x = 0; x < items.length(); x++) {
JSONObject lists = items.getJSONObject(x);
id = lists.getString("primaryKey");
store = lists.getString("store");
product = lists.getString("items");
state = lists.getString("state");
uniqeID = lists.getString("uniqeID");
HashMap<String, String> contacts = new HashMap<String, String>();
contacts.put("id", id);
contacts.put("store", store);
contacts.put("product", product);
contacts.put("state", state);
contacts.put("cbid", uniqeID);
Log.i("pref", "" + listitems);
listitems.add(contacts);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
for (int n = 0; n < listitems.size(); n++) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setId(Integer.parseInt(listitems.get(n).get("cbid")));
cb.setText(listitems.get(n).get("product"));
cb.setTextColor(Color.BLACK);
if (listitems.get(n).get("state").toString().equals("true")) {
cb.setChecked(true);
my_checked_layout.addView(cb);
cb.setBackgroundColor(Color.argb(200, 8, 242, 2));
cb.setTextColor(Color.parseColor("#CFCFCF"));
} else {
cb.setChecked(false);
cb.setBackgroundColor(Color.argb(100, 5, 214, 0));
cb.setTextColor(Color.parseColor("#F7F7F7"));
my_layout.addView(cb);
}
}
Intent in = getIntent();
String name = in.getStringExtra(MainActivity.TAG_FIRSTNAME);
String email = in.getStringExtra(MainActivity.TAG_EMAIL);
String list = in.getStringExtra(MainActivity.TAG_LIST);
String[] seperatedString = list.split(", ");
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
// Array_Count=seperatedString.length;
LinearLayout my_layout = (LinearLayout) findViewById(R.id.test);
/*
* for (int i = 0; i < Array_Count; i++) { TableRow row =new
* TableRow(null); row.setId(i); row.setLayoutParams(new
* LayoutParams
* (LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); CheckBox
* checkBox = new CheckBox(getActivity());
* checkBox.setOnCheckedChangeListener(this); checkBox.setId(i);
* checkBox.setText(seperatedString[i]); row.addView(checkBox);
* my_layout.addView(row); }
*/
lblName.setText(name);
lblEmail.setText(email);
}
The following is my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<!-- Name Label -->
<TextView android:id="#+id/name_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:textColor="#43bd00"/> <!-- green -->
<!-- Email Label -->
<TextView
android:id="#+id/email_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#EB0505" /> <!-- red -->
<!-- Mobile Label -->
<TextView
android:id="#+id/mobile_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#E5FF00"
android:textStyle="bold"
android:text="Empty, Mobile_label"/> <!-- yellow -->
<TextView
android:id="#+id/list_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FF00FF" /> <!-- pink -->
<LinearLayout
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
<LinearLayout
android:id="#+id/checked"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
What i thought would work is just add a number behind the id's
so my could would like like this:
Checkbox cb[n] = new Checkbox(getApplicationContext());
cb[n].setId(...);
cb[n].onClickListener() = new OnClickListener(){
//TODO add unimplemented code
}
But this didn't seem to work out...
Any suggestions?
For Checkboxes, use OnCheckedChangeListener, not OnClickListener.
Also, for ListView, use a ListAdapter, so that you can reuse the views if the user scrolls through the list instead of creating Views for every list item.
Here some sample code:
private class MyArrayAdapter extends ArrayAdapter<Product>{
private MyOnCheckedChangeListener listener;
public MyArrayAdapter(Context context, int resource) {
super(context, resource);
this.listener = new MyOnCheckedChangeListener();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//super call to create / recycle the view
View view = super.getView(position, convertView, parent);
//set the checkbox and text
CheckBox checkBox = (CheckBox) view.findViewById(R.id.list_checkbox);
//set the id of the item in the tag of the checkbox
checkBox.setTag(getItemId(position));
checkBox.setOnCheckedChangeListener(listener);
TextView textView = (TextView) view.findViewById(R.id.list_textView);
textView.setText(getItem(position).getText());
}
#Override
public long getItemId(int position) {
//use the id of the Product as the ItemId
return getItem(position).getId();
}
}
private class MyOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//retrieve the id of the item from the tag of the checkbox
doSomething((Long) buttonView.getTag());
}
}
In the onCreate of your ListView, you have to set the adapter to it:
ArrayAdapter<Product> adapter = new MyArrayAdapter(this, R.layout.list_item);
adapter.addAll(listOfProducts);
listView.setAdapter(adapter);
The layout of the list item:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox android:id="#+id/list_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
<TextView android:id="#+id/list_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/list_checkbox"/>
</RelativeLayout>
Like this, you don't have to create the Views for every item yourself, and you can also add an remove items from the list easily through the adapter.
Here's some further reading about ListViews, including examples:
http://www.vogella.com/tutorials/AndroidListView/article.html
Tinkle showed me the right way..
here is what does the trick for those struggling with the same issue
Private boolean checkstate;
for (int n = 0; n < listitems.size(); n++) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setId(Integer.parseInt(listitems.get(n).get("cbid")));
cb.setText(listitems.get(n).get("product"));
cb.setTextColor(Color.BLACK);
if (listitems.get(n).get("state").toString().equals("true")) {
cb.setChecked(true);
my_checked_layout.addView(cb);
cb.setBackgroundColor(Color.argb(200, 8, 242, 2));
cb.setTextColor(Color.parseColor("#CFCFCF"));
checkstate = true;
} else {
cb.setChecked(false);
cb.setBackgroundColor(Color.argb(100, 5, 214, 0));
cb.setTextColor(Color.parseColor("#F7F7F7"));
checkstate = false;
my_layout.addView(cb);
}
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (checkstate == false) {
Log.i("pref ", "button " + buttonView.getId()
+ "is not enabled");
checkstate = true;
Log.i("pref =", "" + checkstate);
}else {
Log.i("pref", "button is checked");
checkstate = false;
}
}
});
}