Read View's children while initializing View - java

This View is supposed to make a Button for each LinearLayout inside itself, and put that LinearLayout inside a ScrollView. I think the problem is that the LinearLayouts don't exist yet, since they are created AFTER initializing this view. Therefore getChildCound() returns zero. You could work around this by hard coding the number of Buttons or getting it from a XML attribute, but you can't put the LinearLayouts in the ScrollViews, when there are no LinearLayouts. Is there a way to work around this?
code:
package mika.actual;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import java.util.ArrayList;
public class AccordionWidget extends LinearLayout{
public AccordionWidget(Context c, AttributeSet attrs) {
super(c, attrs);
final Context context = c;
final int count = this.getChildCount();
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.accordion);
String[] btns = getResources().getStringArray(R.array.buttons);
ArrayList<LinearLayout> lls = new ArrayList <> (count);
for(int i = 0; i < count; i++){
View child = this.getChildAt(i);
if (child instanceof LinearLayout) {
lls.add((LinearLayout)child);
}
}
for(int i = 0; i < lls.size(); i++){
if(btns[i] == null){
Log.e("error: ", "Please add more Button lables to the strings.xml file.");
}
final Button btn = new Button(context);
final LinearLayout ll = lls.get(i);
final ScrollView sv = new ScrollView(context);
final int col_pressed = a.getColor(R.styleable.accordion_backgroundColorPressed, Color.BLACK);
final int col_unpressed = a.getColor(R.styleable.accordion_backgroundColorUnpressed, Color.YELLOW); //Black and yellow, black and yellow...
LayoutParams btnparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
LayoutParams swparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
LayoutParams llparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
btn.setText(btns[i]);
btn.setBackgroundColor(col_pressed);
llparams.weight = 1f;
btn.setLayoutParams(btnparams);
ll.setLayoutParams(llparams);
sv.setLayoutParams(swparams);
ll.setOrientation(LinearLayout.VERTICAL);
sv.setVisibility(View.GONE);
this.addView(sv);
this.addView(btn);
sv.addView(ll);
btn.setOnClickListener(new OnClickListener() {
private boolean btnstate = false;
#Override
public void onClick(View v) {
if (btnstate) {
btn.setBackgroundColor(col_pressed);
sv.setVisibility(View.VISIBLE);
btnstate = true;
} else {
btn.setBackgroundColor(col_unpressed);
sv.setVisibility(View.GONE);
btnstate = false;
}
}
});
}
a.recycle();
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<mika.actual.AccordionWidget
xmlns:accordion="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
accordion:text_color="#color/text_color"
accordion:backgroundColorPressed="#color/button_pressed"
accordion:backgroundColorUnpressed="#color/button_not_pressed"
android:id="#+id/swaggy"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
</mika.actual.AccordionWidget>

The idea is that you need to put your logic into onLayout
Something like this:
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final Context context = c;
final int count = this.getChildCount();
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.accordion);
String[] btns = getResources().getStringArray(R.array.buttons);
ArrayList<LinearLayout> lls = new ArrayList <> (count);
for(int i = 0; i < count; i++){
View child = this.getChildAt(i);
if (child instanceof LinearLayout) {
lls.add((LinearLayout)child);
}
}
.......
See this
Make sure that you call child.layout() for each child inside this method.

You can create custom LinearLayout inside ScrollView:
<ScrollView>
<LinearLayout android:id="#+id/parent"/>
</ScrollView>
Then Create java class for your layout and inflate it.
See this

Related

Unable to click on custom listview, blocksDescendants not working

I'm fairly new to Android programming and tried everything I could I found on SO, but it still doesn't work.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:fillViewport="true"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.northcityproductions.androidiosapptransfertest1.MainActivity">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false" />
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:id="#+id/imageView1"
android:layout_gravity="center_vertical"
android:clickable="false"
android:padding="5dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:paddingStart="50dip"
android:textSize="20dip"
android:layout_gravity="center_vertical"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:clickable="false"
android:layout_alignParentStart="true">
</TextView>
</RelativeLayout>
AndroidListAdapter.java
package com.northcityproductions.androidiosapptransfertest1;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class AndroidListAdapter extends ArrayAdapter {
List<String> androidListViewStrings = new ArrayList<String>();
List<Drawable> imagesId = new ArrayList<Drawable>();
Context context;
public AndroidListAdapter(Activity context, List<Drawable> imagesId, List<String> textListView) {
super(context, R.layout.activity_main, textListView);
this.androidListViewStrings = textListView;
this.imagesId = imagesId;
this.context = context;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewRow = layoutInflater.inflate(R.layout.activity_main, null,
true);
TextView mtextView = (TextView) viewRow.findViewById(R.id.textView1);
ImageView mimageView = (ImageView) viewRow.findViewById(R.id.imageView1);
mtextView.setText(androidListViewStrings.get(i));
mimageView.setImageDrawable(imagesId.get(i));
return viewRow;
}
}
Finally, MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get list of apps
int flags = PackageManager.GET_META_DATA |
PackageManager.GET_SHARED_LIBRARY_FILES |
PackageManager.GET_UNINSTALLED_PACKAGES;
PackageManager pm = getPackageManager();
List<ApplicationInfo> applications = pm.getInstalledApplications(flags);
List<String> applicationsInstalled = new ArrayList<String>();
List<Drawable> applicationIcons = new ArrayList<Drawable>();
//Create map and sort alphabetically
Map applicationsList = new HashMap();
for (ApplicationInfo appInfo : applications) {
if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
// System application
} else {
// Installed by user
String appName = (String) pm.getApplicationLabel((appInfo));
appName = appName.substring(0, 1).toUpperCase() + appName.substring(1);
applicationsList.put(appName, pm.getApplicationIcon(appInfo));
}
}
Map<String, Drawable> treeApps = new TreeMap<String, Drawable>(applicationsList);
for (Map.Entry<String, Drawable> appMap : treeApps.entrySet()) {
applicationsInstalled.add(appMap.getKey());
applicationIcons.add(appMap.getValue());
}
//Arrange them in listview
final AndroidListAdapter androidListAdapter = new AndroidListAdapter(this, applicationIcons, applicationsInstalled);
ListView lv1 = (ListView) findViewById(R.id.listView1);
lv1.setAdapter(androidListAdapter);
lv1.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("List");
adb.setMessage(" selected Item is="+parent.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
});
}
}
I have tried adding the blocksDescendants code in my activity_main.xml under Listview, and Relativelayout, but that doesn't seem to fix it. I also tried setting the focusable property to false for the imageview and textview but that didn't fix it either.

java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.support.v7.widget.RecyclerView$LayoutParams

I have a RecyclerView with a LinearLayout inside. The LinearLayout consists out of 9 buttons. Before some changes I could click the buttons and it didn't crashed. But after I added this code below it gives the error and does not show where it comes from:
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams
cannot be cast to android.support.v7.widget.RecyclerView$LayoutParams
The imports in Adapter:
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout.LayoutParams;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
Added this in the onClickListener:
tempTag = (int) v.getTag();
mAdapter.grayButton(tempTag / 9, tempTag % 9);
zahl1 = Integer.parseInt(mAdapter.getText(tempTag).toString());
Added this method in the RecyclerView.Adapter:
public void grayButton(int row, int element){
recycleViewDatas.get(row).setGray(element);
notifyItemChanged(row);
}
Added this code in the onBindViewHolder:
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
viewHolder.ll.setLayoutParams(lp);
lp.height = viewHolder.ll.getLayoutParams().height - (int) (viewHolder.buttons.get(j).getLayoutParams().height - recycleViewDatas.get(i).getSize()) + 30;
viewHolder.ll.setLayoutParams(lp);
if(recycleViewDatas.get(i).getGray() == j)
viewHolder.buttons.get(j).setTextColor(Color.GRAY);
else if(recycleViewDatas.get(i).getGray() == -1)
viewHolder.buttons.get(j).setTextColor(Color.BLACK);
This is my ViewHolder:
public static class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout ll;
private ArrayList<Button> buttons = new ArrayList<>();
public ViewHolder(View v, Context context) {
super(v);
ll = (LinearLayout) v.findViewById(R.id.llRecycleView);
for (int i = 0; i < ll.getChildCount(); i++) {
buttons.add((Button) ll.getChildAt(i));
}
}
}
The layout file of the recycleviewdata:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="9"
android:background="#drawable/zeile"
android:id="#+id/llRecycleView">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#android:color/black"
android:background="#android:color/transparent"
android:textSize="23sp"
android:clickable="false"
android:layout_gravity="center"
android:gravity="center" />
...more buttons
The layout of the MainActivity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:background="#drawable/top">
...some buttons
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/></LinearLayout>
I do not understand why the error comes after the update. And the app only crashes on my M9. On the HTC One V it does not crash and all works as expected.
You know the problem? Do you need any more code?
Your problem is in onBindViewHolder:
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
LayoutParams is implemented for (almost) all the layouts.
When you set LayoutParams on a view, you need to set it with a type of the view's parents. So if you have a LinearLayout and you are trying to add a Button, you need to set LinearLayout.LayoutParams on the Button. The problem in this case is that you don't know the parent type. And by that I mean it can different on different Android versions.
The safe bet is to use the LayoutParams from a common class (ViewGroup?) since you only set width and height.
i had same problem, you can use this
ViewGroup.LayoutParams layoutParams =v.itemView.getLayoutParams();
layoutParams.width= ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.height= 200;
v.itemView.setLayoutParams(layoutParams);
if you need the kotlin version :
with(view.layoutParams){
width = ViewGroup.LayoutParams.WRAP_CONTENT
height = ViewGroup.LayoutParams.MATCH_PARENT
}

How to make ViewPager fullscreen?

I have a ViewPager that I want to take the full-screen, but it only takes part of it. How can I make it take the full-screen? Here's my code, notice that it is filled with many calls to make the layout take the full-screen, to no avail.
walkthrough_activity.xml:
<?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.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="1080dp"
android:minHeight="1920dp"/>
</RelativeLayout>
walkthrough_single_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/image_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
WalkthroughActivity.java:
package org.core.game.activities;
import org.core.game.Log;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class WalkthroughActivity extends Activity
{
private static final int MAX_VIEWS = 1;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.walkthrough_activity);
getWindow().setLayout(Main.screenWidth, Main.screenHeight);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new WalkthroughPagerAdapter());
mViewPager.setOnPageChangeListener(new WalkthroughPageChangeListener());
mViewPager.setX(0);
mViewPager.setY(0);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = width;
LayoutParams lp = new LayoutParams(width, height);
mViewPager.setLayoutParams(lp);
}
class WalkthroughPagerAdapter extends PagerAdapter
{
#Override
public int getCount()
{
return MAX_VIEWS;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view == (View) object;
}
#SuppressLint("InflateParams")
#Override
public Object instantiateItem(View container, int position)
{
Log.e("instantiateItem(" + position + ");");
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View imageViewContainer = inflater.inflate(R.layout.walkthrough_single_view, null);
ImageView imageView = (ImageView) imageViewContainer.findViewById(R.id.image_view);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setAdjustViewBounds(true);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = width;
imageView.setLayoutParams(new ViewGroup.LayoutParams(width, ViewGroup.LayoutParams.FILL_PARENT));
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(1080, 1920);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(1080, 1920);
imageView.setLayoutParams(layoutParams);
switch (position)
{
case 0:
imageView.setImageResource(R.drawable.should_be_full_screen);
break;
}
((ViewPager) container).addView(imageViewContainer, 0);
return imageViewContainer;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
((ViewPager) container).removeView((View) object);
}
}
}
And this is how it looks (the image is 1080*1920):
Edit: I basically want to do a mini tutorial. One page with images, one page with a movie. What do you think is the best way?
Try this:
int deviceWidthInPixels = getResources().getDisplayMetrics().widthPixels;
int deviceHeightInPixels = getResources().getDisplayMetrics().heightPixels;
imageView.getLayoutParams().width = deviceWidthInPixels;
imageView.getLayoutParams().height = deviceHeightInPixels;
Also, use this for ViewPager:
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
And this for ImageView
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/image_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
Try this :
<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:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
/>
</LinearLayout>
our code
android:layout_width="fill_parent"
android:layout_height="fill_parent"
Change it to
android:layout_width="match_parent"
android:layout_height="match_parent"
Or you can try this adding to your ViewPager
android:layout_height="0dp"
android:layout_weight="1"
Let me know if further issue exists
-Now i saw your lines
LayoutParams lp = new LayoutParams(width, height);
Change it to Below code:-
Layoutparams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
I feel so stupid... Notice that in my onCreate I have getWindow().setLayout(Main.screenWidth, Main.screenHeight) Annoyingly I made Main.screenHeight) to be 75 % :( Removing it fixed my problem.

android TableLayout adding rows dynamically adds only the last row

after reading tens of threads on StackOverflow.
I'm trying to add dynamically rows to a table-layout.
The problem is, the only one row is added dynamically, and it is spanning on all of the page.
This is my code:
package com.example.trashproject;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
public class MainActivity extends FragmentActivity{
private static final int ROWS =2;
private static final int COLS = 10;
private static final String TAG = null;
private TableLayout mTable;
private View[][] mCircles;
private boolean[][] mData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
makeTable();
}
private void makeTable() {
mTable = (TableLayout) findViewById(R.id.table);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams();
rowParams.width = LayoutParams.WRAP_CONTENT;
rowParams.height = LayoutParams.WRAP_CONTENT;
mCircles = new View[ROWS][COLS];
TableRow row;
for (int i = 0; i < ROWS; i++) {
row = new TableRow(this);
row.setLayoutParams(rowParams);
for (int j = 0; j < COLS; j++) {
mCircles[i][j] = new View(this);
mCircles[i][j].setBackgroundResource(R.drawable.small_circle);
row.addView(mCircles[i][j]);
}
mTable.addView(row);
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT"/>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT"/>
</TableRow>
</TableLayout>
</LinearLayout>
calendar_month_grid.xml:
<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view1"
android:layout_width="wrap_content"
android:layout_height="1dp"
/>
small_circle.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<size android:width="15dp"
android:height="1dp"/>
<solid android:color="#android:color/holo_green_light"/>
</shape>
Your help appreciated...
I think it is the "View" that is giving you a problem. Try replacing it with an ImageView (try it) and I think it will work. If you really want View (not sure why) then set the min height and min width to something like 10dp.
It happened to me once that empty View with wrap content spans the whole page. It is pushing the rest of your rows out of the screen

Right and left align in a single ListView

I am setting a listView dynamically. I will have two things shown on each line that I will be receiving from parse.com. I want the first thing to be left aligned and blue, with the second thing right aligned and red. I will have two arrays, firstArray, and secondArray. I found lots of ways to do this, but none dynamically. How should I go about doing this, or I can do it in xml?
Updated
This is my xml after that tutorial posted by #t0s
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="2dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/column1"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#0000FF"
android:gravity="left"
/>
<TextView
android:id="#+id/center"
android:text="VS"
android:textSize="15sp"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#FFFFFF"
android:gravity="center"
/>
<TextView
android:id="#+id/column2"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#FF0000"
android:gravity="right"
/>
</LinearLayout>
and my java
ListView list = (ListView) findViewById(R.id.mylist);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.mylist, namesArray);
list.setAdapter(listAdapter);
//find my objects off parse, and call this method
private String display(Object name, Object record,
ArrayAdapter listAdapter) {
String fightCard = (name).toString();
namesArray.add((name).toString() +" " + (record).toString());
return fightCard;
}
Well my code is a mess.
Check the tutorial here is [very simple]
Ok Chad check here the code :
Main Activity :
package org.example.chad;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
public class MainActivity extends ListActivity {
private ArrayList<DataItem> data = new ArrayList<DataItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//create Objects
DataItem obj1 = new DataItem("name1", "record1");
DataItem obj2 = new DataItem("name2", "record2");
DataItem obj3 = new DataItem("name3", "record3");
DataItem obj4 = new DataItem("name4", "record4");
DataItem obj5 = new DataItem("name5", "record5");
//add the to ArrayList
data.add(obj1);
data.add(obj2);
data.add(obj3);
data.add(obj4);
data.add(obj5);
CustomAdapter adapter = new CustomAdapter(this, R.layout.row, data);
setListAdapter(adapter);
}
}
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" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
DataItem :
package org.example.chad;
public class DataItem {
private String name;
private String record;
public DataItem(){
}
public DataItem(String n, String r ){
this.name = n;
this.record = r;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getrecord() {
return record;
}
public void setrecord(String record) {
this.record = record;
}
}
CustomAdapter :
package org.example.chad;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<DataItem> {
private ArrayList<DataItem> objects;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<DataItem> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.row, null);
}
DataItem i = objects.get(position);
if (i != null) {
TextView nameView = (TextView) v.findViewById(R.id.name);
TextView recordView = (TextView) v.findViewById(R.id.record);
if (nameView != null){
nameView.setText(i.getname());
}
if (recordView != null){
recordView.setText(i.getrecord());
}
}
return v;
}
}
and row.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="horizontal" >
<TextView
android:id="#+id/name"
android:layout_width="100sp"
android:layout_height="20sp"
android:textSize="16sp"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10sp"/>
<TextView
android:id="#+id/record"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_marginLeft="10sp"
android:layout_gravity="right"
android:textSize="16sp" />
</LinearLayout>
In a couple of hours I will add some comments.
The result is here
If im not mistaken you have to extend BaseAdapter class so you have a custom Adapter for your ListView, it is not possible to add two array items to a ListView without creating a custom adapter.
here is a tutorial.
is not as hard as it looks like. Hope it helps.

Categories

Resources