Android: set xml layout to table row? - java

I have table, which is described in main xml layout. I need to know, if there is any chance to set layout to each table row, so I don't need to recreate each time? Where layout is simple, I can do that by code, but at this time layout is pretty complicated.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ebank_saskaitos);
this.setFirstBlock();
}
private void setFirstBlock() {
TableLayout ll = (TableLayout) findViewById(R.id.first_block);
ll.addView(this.tableChild());
}
private TableRow tableChild() {
TableRow tr = new TableRow(this);
//row implementation
return tr;
}

use LayoutInflater like this way:
private View tableChild() {
TableRow tr = new TableRow(this);
View v = LayoutInflater.from(mContext).inflate(R.layout.layout_for_my_table_row, tr, false);
//want to get childs of row for example TextView, get it like this:
TextView tv = (TextView)v.findViewById(R.id.my_row_text_view);
tv.setText("This is another awesome way for dynamic custom layouts.");
return v;//have to return View child, so return made 'v'
}

Related

CursorAdapter Listview recycling wrong

I created the following CursorAdapter which shows messages from my SQL database, everything is added well until I scroll the list, I know that the objects are recycled, but in a wrong way. Here is my CursorAdapter class:
public class ChatAdapter extends CursorAdapter {
public ChatAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.chat_item, parent,
false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView left = (TextView) view.findViewById(R.id.lefttext);
TextView right = (TextView) view.findViewById(R.id.righttext);
LinearLayout rightBubble = (LinearLayout) view
.findViewById(R.id.right_bubble);
LinearLayout leftBubble = (LinearLayout) view
.findViewById(R.id.left_bubble);
TextView leftDate = (TextView) view.findViewById(R.id.leftdate);
TextView rightDate = (TextView) view.findViewById(R.id.rightdate);
// Extract properties from cursor
String from = cursor.getString(cursor.getColumnIndexOrThrow("from"));
String txt = cursor.getString(cursor.getColumnIndexOrThrow("message"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("t"));
String id = cursor.getString(cursor.getColumnIndexOrThrow("id"));
// Parse time
long datevalue = Long.valueOf(date) * 1000;
Date dateformat = new java.util.Date(datevalue);
String convert = new SimpleDateFormat("HH:mm").format(dateformat);
// Populate fields with extracted properties
if (from.equals("me")) {
right.setText(txt);
left.setText("");
rightBubble
.setBackgroundResource(R.drawable.balloon_outgoing_normal);
leftBubble.setBackgroundDrawable(null);
rightDate.setText(convert);
leftDate.setVisibility(View.GONE);
}
else {
left.setText(txt);
right.setText("");
leftBubble
.setBackgroundResource(R.drawable.balloon_incoming_normal);
rightBubble.setBackgroundDrawable(null);
leftDate.setText(convert);
rightDate.setVisibility(View.GONE);
}
}
}
Unfortenately, after scrolling the list, dates from the rightDate and leftDate dissapears after moving back. I think it't due the .setVisibility(View.GONE)
Any suggestions to fix this?
when the view is recycled, it is in the previous state, android did not clear the status for you.
To fix your problem, you have to set the view in question to VISIBLE when needed
Edit:
like this, add the 2 lines
if (from.equals("me")) {
// your original code
rightDate.setVisibility(View.VISIBLE); //add this
}
else {
// your original code
leftDate.setVisibility(View.VISIBLE); //add this
}

Android TableLayout.addView() does not really work

I'm trying to fill my TableLayout with some views with the method addView.
This is what I try to do:
private void createNewTable(){
tableLayout = (TableLayout) getView().findViewById(R.id.tableLayout1);
for(int i = 0; i < objectList.size(); i++){
if(objectList.get(i).getType() == 0){
tableLayout.addView(createLocationObjectInTable((LocationObject)objectList.get(i)), i);
}
}
}
and the createObjectInList method:
private View createLocationObjectInTable(LocationObject locObject) {
TableRow tr = new TableRow(getActivity());
View v = LayoutInflater.from(getActivity()).inflate(R.layout.view_layout, tr, false);
TextView textViewCityName = (TextView) v.findViewById(R.id.textView_City_Name);
TextView textViewCityProvider = (TextView) v.findViewById(R.id.textView_City_Provider);
textViewCityName.setText(locObject.getTitle());
textViewCityProvider.setText(locObject.getSubTitle());
return v;
}
But the views aren't displayed in the tableLayout. Logcat doesn't give me any error message, and when I try to do stuff after the line
tableLayout.addView(createLocationObjectInTable((LocationObject)objectList.get(i)), i);
nothing happend. The app just do nothing after this line.
Hope anyone can tell me my mistake?
You don't add your view to TableRow, instead you just add view to TableLayout. Try this:
private View createLocationObjectInTable(LocationObject locObject) {
...
textViewCityProvider.setText(locObject.getSubTitle());
tr.addView(v);
return tr;
}

how to display output in textview using android?

i am newbie in android and i m not getting how to produce this output:
Discipline name:1
{ complete for loop code execute from 0 to 9
}
then it will come outside and will update textview text:ie
Discipline name:2
and will enter inside For Loop
{
complete for loop code execute from 0 to 9
}
here is the java code:
public class SummaryDetailActivity extends Activity
{ TableLayout summaryDetailDisciplineTableLayout;
LayoutInflater mInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summarydetail_view);
mInflater = getLayoutInflater();
summaryDetailDisciplineTableLayout = (TableLayout)findViewById(R.id.summaryDetail_disciplinetable);
//PLEASE SEE THESE LINE OF CODE:
for(int i=0;i<2;i++)
{
TextView disciplineTextView = (TextView)findViewById(R.id.summaryDetail_disciplinetext);
disciplineTextView.setText("discipline name: "+i);
for(int j=0;j<10;j++)
{TableRow disciplineRow = (TableRow) mInflater.inflate(R.layout.summarydetailrow_view,null);
TextView disciplineDeviceLabel = (TextView) disciplineRow.findViewById(R.id.summaryDetail_info1);
TextView disciplineQuantityLabel = (TextView)disciplineRow.findViewById(R.id.summaryDetail_hypen);
TextView disciplineLocationLabel = (TextView) disciplineRow.findViewById(R.id.summaryDetail_info2);
disciplineDeviceLabel.setText("device no." + j);
disciplineQuantityLabel.setText("quantity No." + j);
disciplineLocationLabel.setText("Location No." + j);
disciplineRow.setId(j);
summaryDetailDisciplineTableLayout.addView(disciplineRow);
}
}
}
}
this code is producing this output:
Why your code is not working the way you want. Is because this
TextView disciplineTextView = (TextView)findViewById(R.id.summaryDetail_disciplinetext);
is initiate as static view that can't be clone in your loop. That's why the value
of the discipline name is 1 not 0. The loop only update the value not clone the view.
You should do this
TextView disciplineTextView = new Textview(this);
disciplineTextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
disciplineTextView.setText("discipline name: "+i);
summaryDetailDisciplineTableLayout.addView(disciplineTextView);
for(int j=0;j<10;j++) {
-your code-
}
You should change the xml structure for better UI.
Hope this helps.
Here's how I would've done it.
Inside my XML code, I would create a LinearLayout and within that, a TableLayout.
After fetching the id of my TableLayout, I would dynamically create TableRows and TextViews. You can set their layouts using TableRow.LayoutParams or LayoutParams. You can simply set the text after that and just add them onto the TableRow that you add to TableLayout.
Hope this suggestion helps !
I think that in onCreate() you should use inflater first and then set the view that you have just inflated.
Try this:
View view = getLayoutInflater().inflate(R.layout.summarydetail_view, null);
setContentView(view);

Create a button and add it to a view programmatically

I'm creating a version of the popular Minesweeper game for Android. I'm trying to programmatically create a button and add it to a RelativeLayout. I've found something very similar here: How do I programmatically add buttons into layout one by one in several lines?
When I try to run it I get a NullPointerException at:
RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game);
Here's the whole block of code:
public void create() {
RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game);
for(int i = 0; i < gridSize; i++) {
if(grid[i] == 0) { //if grid pos. indicates an empty cell
Button empty = new Button(this);
empty.setBackgroundResource(R.drawable.emptybutton); //set background to empty
empty.setId(i); //set id to value of i
empty.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout1.addView(empty); //add the button to the relativeLayout view
//((Button) findViewById(i)).setOnClickListener(emptyListener);
}
Thanks in advance for any responses
have set the layout xml of the Activity by setContentView(R.layout.xxxx)?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
...
this
RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game);
should be
RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.relative_id);
R.id... used for mapping control and RelativeLayout is a control.
I think you're getting a blank screen because you haven't set the content view.
What i mean is that the codes does what it's supposed to do however, you should remove the "setContentView()" method at the top and place it at the end, then you should set it to the RelativeLayout before you close the onCreate() method! Something like this:
public void create() {
RelativeLayout layout1 = new RelativeLayout(this);
for(int i = 0; i < gridSize; i++) {
if(grid[i] == 0) { //if grid pos. indicates an empty cell
Button empty = new Button(this);
empty.setBackgroundResource(R.drawable.emptybutton); //set background to empty
empty.setId(i); //set id to value of i
empty.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout1.addView(empty); //add the button to the relativeLayout view
//((Button) findViewById(i)).setOnClickListener(emptyListener);
}
}
setContentView(layout1);
}
Also notice that I've changed the declaration of the Relativelayout a little bit.
I hope this helps. :) !
You must enter the ID of the RelativeLayout, not the xml fil name.
try with
RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.yourRelativeLayoutViewID);

How to display Images in Android on Runtime & make radio buttons as radio groups in List

Updated code snipped as asked:
int MovieNum=children.size();
String[] MovieName=new String[MovieNum];
String[] MovieCover=new String[MovieNum];
RadioGroup rg = new RadioGroup (this);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton rb[]= new RadioButton[children.size()];
//LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
//LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
//layout.addView(rg, p);
for (int i = 0; i < children.size(); i++)
{
Element movieAtt = (Element)doc.getRootElement().getChild("movies").getChildren("movie").get(i);
MovieName[i]=movieAtt.getAttributeValue( "Title" );
MovieCover[i]=movieAtt.getAttributeValue( "cover" );
ShowTime[i]=movieAtt.getAttributeValue( "showtime" );
TweetText+=" I will see "+movieAtt.getAttributeValue("Title");
System.out.println(TweetText);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.rowlayout, R.id.label, MovieName);
//setListAdapter(adapter);
//String item = (String) getListAdapter().getItem(position);
rb[i] = new RadioButton(this);
rb[i].setText(movieAtt.getAttributeValue("Title"));
rg.addView(rb[i]);
//Calling this func to get Images
//LoadImageFromWebOperations(movieAtt.getAttributeValue( "cover" ));
}
}
}
catch (MalformedURLException e1)
{
e1.printStackTrace();
System.out.println("ErrorThrowedIs: "+e1);
Toast.makeText(getBaseContext(), e1.toString(),5);
}
}
public static Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e)
{
return null;
}
}
//Updated code ends here
I have to display 3 things in my list View. One is going to be a Radio button corresponding to every row. I can not use Radio group as i am not aware of the list length which is dynamically generated. So i can not set it as Radio group.
I wish to know how can i do the same.
Also what i am doing is, i want to get an image along in the same list for every row which is created from the path i get at runtime.
So during my program, i would get these values :
for (int i = 0; i < mvLen; i++)
{
Element movieAtt = (Element)doc.getRootElement().getChild("movies").getChildren("movie").get(i);
MovieName[i]=movieAtt.getAttributeValue( "Title" );
MovieCover[i]=movieAtt.getAttributeValue( "cover" );
ShowTime[i]=movieAtt.getAttributeValue( "showtime" );
Now clearly this is an string array of Movie
Names in MovieName and array of strings of URL for the cover of that movie. I wish to display all those images in front of the Movie Names. My list adapter and corrosponding XML file are listed as below. Can anyone suggest changes/hints for the same . I have been reading http://www.vogella.de/articles/AndroidListView/article.html as well. But could not figure out much to meet my requirements.
So. Create RadioGroup in your class RadioGroup radioGroup = new RadioGroup(this); and simply add radiobuttons to it when you filling content radioGroup.addView(radioButton);
Summary:
RadioGroup radioGroup = new RadioGroup(this);
//Cycle begin
RadioButton rButton = (RadioButton)findViewById(R.id.my_radiobutton);
// OR
RadioButton radioButton = new RadioButton(this);
radioButton .setText(R.string.radio_group_snack);
radioButton .setId(R.id.snack);
radioGroup.addView(rButton);
radioGroup.addView(radioButton);
//Cycle end
Example of custom adapter and getview method(it's 100% work code):
public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String[] users = getUsers(); //it returns list of users in String array
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.main, parent, false);
TextView label=(TextView)row.findViewById(R.id.label); //TextView decalred in my layout xml file
label.setText(users[position]);
ImageView icon=(ImageView)row.findViewById(R.id.icon); //ImageView decalred in my layout xml file
byte[] bb = getAvatar(users[position]); //some method where I get image for user. It not interesting for us so I cut it from here...
if(bb != null && bb.length != 0){
icon.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length)); //SET IMAGE FOR ROW
icon.setVisibility(View.VISIBLE); //SET VISIBILITY OF IMAGE
}
//RIGHT HERE YOU CAN MANIPULATE WITH YOUR RADIOBUTTONS. FOR EXAMPLE:
RadioButton rButton = (RadioButton)findViewById(R.id.my_radio_button);
radioGroup.addView(rButton); //WHERE radioGroup IS RADIOGROUP YOU INITIALIZED BEFORE;
return row;
}
}
}
And this is my onCreate method:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
db.open();
String[] users = db.getUsersList();
ListView listView = getListView();
this.setListAdapter(new MyCustomAdapter(this, R.layout.main, users));
db.close();
}
For each row in the list get the radioButton and add it to the RadioGroup.
You might have to create all the radioButton's upfront and store them in a list.Set them in the ContentView depending on the position

Categories

Resources