In the following code, I have a options menu and when I select the menu option, I want to update the textview. Setting the text initially works fine and no errors are generated. Here is the code where the settext isn't working. I have put in debug statements and the code is getting hit, but text not updating. I put arrows next to the code that isn't updating. Review other textview examples, but can't figure it out.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_Bflat:
if (VERBOSE) Log.v(TAG, "+++ menu_item_Bflat +++");
// BFLAT = 1
mKeySelected = BFLAT;
>>>> mChapterSelected.setText("B Flat");
return true;
case R.id.menu_item_Eflat:
// EFLAT = 2
mKeySelected = EFLAT;
>>>> mChapterSelected.setText("E Flat");
return true;
default:
return super.onOptionsItemSelected(item);
} // switch
} // onOptionsItemSelected
Here is the rest of my code, if needed:
public class ChapterListFragment extends ListFragment {
private static final boolean VERBOSE = true;
private ArrayList<Chapters> mChapters;
private static final String TAG = "ChapterListFragment";
private static final int BFLAT = 1;
private static final int EFLAT = 2;
private TextView mChapterSelected;
private View mView;
private int mKeySelected;
#Override
public void onCreate(Bundle savedInstanceState) {
if (VERBOSE) Log.v(TAG, "+++ onCreate +++");
super.onCreate(savedInstanceState);
// Must explicitly tell Fragment Manager that the fragment should receive a call to
// onCreateOptionsMenu().
setHasOptionsMenu(true);
// Get the view for the Fields
if (mView == null) {
mView = getActivity().getLayoutInflater()
.inflate(R.layout.activity_improvisation, null);
}
getActivity().setTitle(R.string.chapters_title);
mChapters = ChapterList.get(getActivity()).getChapters();
ChapterAdapter adapter = new ChapterAdapter(mChapters);
setListAdapter(adapter);
mChapterSelected = (TextView) mView.findViewById(R.id.chapter_selected);
mChapterSelected.setText("Chapter Selected Here");
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Get the chapter from the adapter
Chapters c = ((ChapterAdapter)getListAdapter()).getItem(position);
//Start ImprovisationActivity
Intent i = new Intent(getActivity(), ImprovisationActivity.class);
i.putExtra(ChapterFragment.EXTRA_CHAPTER_ID, c.getId());
i.putExtra(ChapterFragment.EXTRA_KEYSELECTED, mKeySelected);
startActivity(i);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_chapters_list, menu);
}
Here is the XML file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_weight="2"
android:layout_height="fill_parent"
android:layout_width="match_parent"
>
<VideoView
android:id="#+id/video_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
<LinearLayout
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/chapter_selected"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity = "center"
android:textStyle="bold"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:text="Chapter Selection"
/>
</LinearLayout>
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_height="match_parent"
android:layout_width="match_parent"
/>
</LinearLayout>
I didn't find out why I couldn't setText, but displaying subtitles after the user selects a menu item works well for my purposes.
Related
My app is properly populating a ListView. I need to find out the contents of a specific TextView when the user taps on the row. I don't need the RowID, and due to how the app works, I can't use OnClickEvent.
How can I get the currently displayed contents of the TextView on the tapped row?
EDIT:
Below is how I implemented the suggestion to use onItemClick. My layout uses a FrameLayout to allow for tapping on the right or left side of a row. Depending on the side tapped, it triggers a different activity. Both activities need the contents of the TextView called bonusListCode, which is what I'm trying to fetch.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG,"Entered onItemClickListener");
Intent nextActivity = new Intent(bonusListing.this, bonusListing.class);
startActivity(nextActivity);
}
When I tap on my cell, it goes to the appropriate activity, but I don't see the log entry that the above code should trigger, so it isn't being triggered. What am I doing wrong in the onItemClickListener?
EDIT 2: I am seeing some older posts that indicated it might be easier to pull this from my cursor since I'm using a SimpleCursorAdapter. Below is mine:
// Populate the ListView w/ all rows
Cursor data = appDBHelper.getAppDataAllBonuses();
listView.setAdapter(new SimpleCursorAdapter(this, R.layout.bonus_list_row_item, data,
new String[] {"sCode", "sName", "sCategory", "sCity", "sState"},
new int[] {R.id.bonusListCode, R.id.bonusListName, R.id.bonusListCategory, R.id.bonusListCity, R.id.bonusListState}, 0));
Edit 3: Additional code per request.
Here is my bonusListing.java file, which is how I'm populating the ListView.
public class bonusListing extends AppCompatActivity {
private static String TAG = "bonusListing"; // Tag just for the LogCat window
SharedPreferences sharedpreferences;
UserDataDBHelper userDBHelper;
AppDataDBHelper appDBHelper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bonus_listing);
sharedpreferences = getSharedPreferences(tohPreferences,
Context.MODE_PRIVATE);
Toolbar myToolbar = findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
ListView listView = findViewById(R.id.lvBonusData);
// Handle the appData DB.
appDBHelper = new AppDataDBHelper(this);
try {
Log.e(TAG,"Calling createDatabase");
appDBHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to CREATE DATABASE");
}
// Populate the ListView w/ all rows
Cursor data = appDBHelper.getAppDataAllBonuses();
listView.setAdapter(new SimpleCursorAdapter(this, R.layout.bonus_list_row_item, data,
new String[] {"sCode", "sName", "sCategory", "sCity", "sState"},
new int[] {R.id.bonusListCode, R.id.bonusListName, R.id.bonusListCategory, R.id.bonusListCity, R.id.bonusListState}, 0));
// Print to Log the DB headers
CommonSQLiteUtilities.logDatabaseInfo(appDBHelper.getWritableDatabase());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG,"Entered onItemClickListener");
Intent nextActivity = new Intent(bonusListing.this, bonusListing.class);
startActivity(nextActivity);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Log.e(TAG,"action_setting");
startActivity(new Intent(this, appSettings.class));
return true;
case R.id.action_trophyMode:
Log.e(TAG,"action_trophyMode");
startActivity(new Intent(this, trophyMode.class));
return true;
case R.id.action_filter:
Log.e(TAG,"action_filter");
// Populate the ListView w/ filtered data
ListView listView = findViewById(R.id.lvBonusData);
Cursor data = appDBHelper.getAppDataFilteredBonuses();
listView.setAdapter(new SimpleCursorAdapter(this, R.layout.bonus_list_row_item, data,
new String[] {"sCode", "sName", "sCategory", "sCity", "sState"},
new int[] {R.id.bonusListCode, R.id.bonusListName, R.id.bonusListCategory, R.id.bonusListCity, R.id.bonusListState}, 0));
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar, menu);
return true;
}
public int getIdFromClassName(String className){
String query = "SELECT rowid" +
" FROM " + CLASSES_TABLE_NAME +
" WHERE " + CLASSES_COLUMN_NAME + " = ?;";
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.longForQuery(db, query, new String[]{ className });
}
public void goToAppSettings (View View) {
Log.e(TAG,"goToAppSettings");
Intent goToAppSettings = new Intent(this,appSettings.class);
startActivity(goToAppSettings);
}
public void goToTrophyMode (View View) {
Log.e(TAG,"goToTrophyMode");
Intent goToTrophyMode = new Intent(this,trophyMode.class);
startActivity(goToTrophyMode);
}
public void goToCaptureBonus (View View) {
String tappedBonus = ((TextView) findViewById(R.id.bonusListCode)).getText().toString();
Log.e(TAG,"goToCaptureBonus, tapped bonus = " + tappedBonus);
Intent goToCaptureBonus = new Intent(this,captureBonus.class);
goToCaptureBonus.putExtra("codeTapped",tappedBonus);
startActivity(goToCaptureBonus);
}
public void goToBonusDetail (View View) {
String tappedBonus = ((TextView) findViewById(R.id.bonusListCode)).getText().toString();
Log.e(TAG,"goToBonusDetail, tapped bonus = " + tappedBonus);
Intent goToBonusDetail = new Intent(this,bonusDetail.class);
goToBonusDetail.putExtra("codeTapped",tappedBonus);
startActivity(goToBonusDetail);
}
}
EDIT 4: Layout file. Here is my bonus_list_row_item.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<ImageView
android:id="#+id/bonusListImage"
android:contentDescription="#string/mainImageDescription"
android:layout_width="64dp"
android:layout_height="48dp"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginEnd="8dp"
android:src="#drawable/no_image_taken" />
<TextView
android:id="#+id/bonusListName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#id/bonusListImage"
android:text="#string/valueBonusName" />
<TextView
android:id="#+id/bonusListCategory"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/bonusListName"
android:layout_toEndOf="#id/bonusListImage"
android:text="#string/valueCategory" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:orientation="horizontal"
android:layout_below="#+id/bonusListCategory"
android:layout_toEndOf="#id/bonusListImage">
<TextView
android:id="#+id/bonusListCode"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="#string/valueBonusCode" />
<TextView
android:id="#+id/bonusListCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="textEnd"
android:text="#string/valueBonusCity"
android:textStyle="bold" />
<TextView
android:id="#+id/bonusListState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="textEnd"
android:layout_marginStart="4dp"
android:text="#string/valueBonusState"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false">
<FrameLayout
android:id="#+id/leftSideRowTapper"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0.0"
android:onClick="goToBonusDetail"
android:layout_weight="1"/>
<FrameLayout
android:id="#+id/rightSideRowTapper"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0.0"
android:onClick="goToCaptureBonus"
android:layout_weight="1"/>
</LinearLayout>
</FrameLayout>
and in case it is useful, here is the activity_bonus_listing.xml as well.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:layout_alignParentTop="true"/>
<ListView
android:id="#+id/lvBonusData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar">
</ListView>
</RelativeLayout>
You don't have to implement OnClickEvent instead impelement OnItemClickListener like this:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Toast.makeText(SuggestionActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
Please, help me to find a solution how to set my checkboxes visible when I click on menu item "delete" and set invisible when I press "confirm" or "cancel".
I use SimpleCursorAdapter, cuz listview is filled from database with cursor loader...
here is my code:
MainActivity
public class MainActivity extends ActionBarActivity implements LoaderManager.LoaderCallbacks<Cursor>{
final String LOG = "phonebookLogs";
private static final int LOADER_ID = 1;
Intent intentAddContact;
ListView lvMain;
CheckBox cbxList;
MenuItem addContact, deleteContact, settings, expimp, confirmDelete, cancelDelete;
DB mDB;
SimpleCursorAdapter scAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find ListView
lvMain = (ListView)findViewById(R.id.lvMain);
//calling for creating adapter
onCreateAdapter();
}
public void onCreateAdapter(){
String[] from = new String[] { DB.COL_LINK, DB.COL_SURNAME, DB.COL_NAME };
int[] to = new int[] { R.id.ivPhoto, R.id.tvSurname, R.id.tvName, };
if(to[0] == 0){
to[0] = R.drawable.default_contact;
}
scAdapter = new SimpleCursorAdapter(this, R.layout.item, null, from, to, 0);
lvMain.setAdapter(scAdapter);
// loader for reading data
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}
public void deleteRecord(){
//when MenuItem "Delete" is clicked
addContact.setVisible(false);
deleteContact.setVisible(false);
settings.setVisible(false);
expimp.setVisible(false);
confirmDelete.setVisible(true);
cancelDelete.setVisible(true);
}
public void onCancelDeleteRecord(){
////when MenuItem "cancel" is clicked
addContact.setVisible(true);
deleteContact.setVisible(true);
settings.setVisible(true);
expimp.setVisible(true);
confirmDelete.setVisible(false);
cancelDelete.setVisible(false);
}
public void confirmDeleteRecord(){
////when MenuItem "confirm" is clicked
addContact.setVisible(true);
deleteContact.setVisible(true);
settings.setVisible(true);
expimp.setVisible(true);
confirmDelete.setVisible(false);
cancelDelete.setVisible(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
//find all MenuItems
addContact = menu.findItem(R.id.addContact);
deleteContact = menu.findItem(R.id.deleteContact);
settings = menu.findItem(R.id.settings);
expimp = menu.findItem(R.id.expimp);
confirmDelete = menu.findItem(R.id.confirmDelete);
cancelDelete = menu.findItem(R.id.cancelDelete);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.addContact:
intentAddContact = new Intent(this, NewContact.class);
startActivity(intentAddContact);
break;
case R.id.deleteContact:
deleteRecord();
break;
case R.id.settings:
break;
case R.id.expimp:
break;
case R.id.confirmDelete:
confirmDeleteRecord();
break;
case R.id.cancelDelete:
onCancelDeleteRecord();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle bndl) {
return new MyCursorLoader(this, mDB);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
scAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
scAdapter.swapCursor(null);
}
}
DB.class and CursorLoader.class are fine, simple query and loading.
and my XML-file for ListView
<?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="wrap_content"
android:layout_margin="#dimen/margin"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin"
android:layout_weight="0.5"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin"
android:orientation="vertical" >
<ImageView
android:id="#+id/ivPhoto"
android:layout_width="#dimen/imageWidth"
android:layout_height="#dimen/imageHeight"
android:layout_gravity="center_vertical"
android:contentDescription="#string/photoDescription"
android:src="#drawable/default_contact" />
</LinearLayout>
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/margin"
android:text=""
android:textSize="#dimen/textSize" />
<TextView
android:id="#+id/tvSurname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/margin"
android:text=""
android:textSize="#dimen/textSize" />
</LinearLayout>
<CheckBox
android:id="#+id/cbxList"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="#dimen/margin"
android:layout_weight="0.2"
android:visibility="invisible" />
</LinearLayout>
I have read a lot already, but how to realize it without creating my own adapter still can't get...
will be thanksfull to any help in finding solution!
You can set your checkbox as visible with: cbxlist.setVisibility(View.VISIBLE);
And if you want it completely gone, use (ie make it look as if it was never added): cbxlist.setVisibility(View.GONE);
If you want it to be just invisible, but still occupy the same space: cbxlist.setVisibility(View.INVISIBLE);
Edit:
for(int i = 0; i < lvMain.getChildCount(); i++) {
lvMain.getChildAt(i).findViewById(R.id.cbxList).setVisibility(View.VISIBLE);
}
That should set all of your checkbox's to visible. Similarly call for View.INVISIBLE when required.
If you want to change visibility of each checkbox in your listview (assuming your XML is your list row view), you need to create your custom adapter and override getView method.
In there, you will do the following:
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
cBox = (CheckBox ) convertView.findViewById(R.id.cbxList);
cBox.setVisibility(View.GONE);
return convertView;
}
Who have simple example for Drop Down Menu by Button Click?
Need make list for installed programs and select for starting.
Menu listMenu = null;
listMenu.add("quasatron"); listMenu.add("magnetron"); listMenu.add("atarrilix");
onCreateOptionsMenu(listMenu);
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.popup_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.food:
makeToast("food","","","");
return true;
case R.id.other:
makeToast("other","","","");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And XML file of popup_menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/food" android:title="Food" />
<item android:id="#+id/other" android:title="Other" />
</menu>
This example is create myself to when you select any item in dropdown (spinner) list at a moment image display rightside on base on select item. so this example help to you.
MainActivity.java
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] technology = {"PHP", "Ruby", "Java", "SQL"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, technology);
final Spinner spinnertech = (Spinner) findViewById(R.id.spinnertech);
spinnertech.setAdapter(adapter);
spinnertech.setOnItemSelectedListener(this);
// Spinner Start....
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position = arg0.getSelectedItemPosition();
ImageView ivtech = (ImageView) findViewById(R.id.imgtech);
if(position == 0) {
ivtech.setImageResource(R.drawable.php);
} else if(position == 1) {
ivtech.setImageResource(R.drawable.ruby);
} else if(position == 2) {
ivtech.setImageResource(R.drawable.java);
} else if(position == 3) {
ivtech.setImageResource(R.drawable.sql);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
// Spinner End....
}
main.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/TableLayout1"
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=".MainActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imgtech"
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_marginRight="10dp" />
<Spinner
android:id="#+id/spinnertech"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="1" />
</LinearLayout>
</TableLayout>
I want to create a simple Page Control in android.... I want to move from one page to another page scrolling horizontally, like the home screen in android device.
I have multiple layout in xml like main.xml, layout_first.xml, layout_second.xml and layout_third.xml
Now I have a simple button in my layout_first.xml, I want to implement a click listener for the button like
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
}
});
No I don't know where to put the above code
Here is my main.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">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Main Layout"
android:textAppearance="?android:attr/textAppearanceLarge" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/myfivepanelpager"/>
</LinearLayout>
Here is my layout_first.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" >
<TextView
android:id="#+id/myTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Layout"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Here is my layout_second.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" >
<TextView
android:id="#+id/myTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Layout"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Here is my layout_third.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" >
<TextView
android:id="#+id/myTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Third Layout"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Here is my java code
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
#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;
}
private class MyPagerAdapter extends PagerAdapter
{
#Override
public int getCount()
{
// TODO Auto-generated method stub
return 3;
}
public Object instantiateItem(View collection, int position)
{
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position)
{
case 0:
resId = R.layout.layout_first;
break;
case 1:
resId = R.layout.layout_second;
break;
case 2:
resId = R.layout.layout_third;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
}
After View view = inflater.inflate(resId, null); add the following:
if(position == 0){
view.findViewById(R.id.button).setOnClickListener(new OnClickListener() {
public void onClick(View v){
}
});
}
This is the new code, It doesn't throw exceptions, but I can't see my custom control "Second". This is the new code:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/L1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
<Button
android:id="#+id/addButton"
android:layout_width="74dp"
android:layout_height="wrap_content"
android:text="Add" />
<EditText
android:id="#+id/newEditText"
android:layout_width="174dp"
android:layout_height="wrap_content"
android:layout_weight="3.24"
android:ems="10"
android:inputType="text" />
</LinearLayout>
<LinearLayout
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
This is the custom control: second.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/secodView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/expandButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.44"
android:text = "Expand"/>
<TextView
android:id="#+id/txtView"
android:layout_width="253dp"
android:layout_height="wrap_content"
android:layout_weight="0.56"
android:ems="10"
android:text = "LOL"/>
</LinearLayout>
<RadioGroup
android:id="#+id/ratingRadioGroup"
android:layout_width="321dp"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/likeButton"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:checked="true"
android:text="Like" />
<RadioButton
android:id="#+id/dislikeButton"
android:layout_width="147dp"
android:layout_height="wrap_content"
android:text="Dislike" />
</RadioGroup>
</LinearLayout>
Second.java class:
public class Second extends ViewGroup
{
private Button mExpandButton;
private RadioButton mLikeButton;
private RadioButton mDislikeButton;
private TextView mText;
private RadioGroup mLikeGroup;
private ViewGroup vGroup;
OnClickListener myClickListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
String s= mExpandButton.getText().toString();
if (s.equals("One Click"))
mExpandButton.setText("Other Click");
else
mExpandButton.setText("One Click");
}
};
OnCheckedChangeListener myCkeckListener = new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if (mLikeButton.isChecked())
mText.setText("I Like it");
if (mDislikeButton.isChecked())
mText.setText("I Don't Like it");
}
};
public Second(Context context)
{
super(context);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = LayoutInflater.from(context).inflate(R.layout.second, this, true);
mText = (TextView)this.findViewById(R.id.txtView);
mExpandButton = (Button) this.findViewById(R.id.expandButton);
mLikeGroup = (RadioGroup)this.findViewById(R.id.ratingRadioGroup);
mExpandButton.setOnClickListener(myClickListener);
mLikeGroup.setOnCheckedChangeListener(myCkeckListener);
//inflater.inflate(R.layout.second, null);
}
#Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4)
{
// TODO Auto-generated method stub
}
}
ActivityMain.java class, where the activity gets started:
public class MainActivity extends Activity
{
protected LinearLayout mList;
protected EditText mEditText;
protected Button mButton;
Second[] sec;
boolean unavez;
OnClickListener myClickListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (LinearLayout)findViewById(R.id.List);
mEditText = (EditText)findViewById(R.id.newEditText);
mButton = (Button)findViewById(R.id.addButton);
sec = new Second[4];
unavez = true;
for (int i=0; i<4; i++)
sec[i]= new Second(this);
}
#Override
protected void onStart()
{
super.onStart();
}
#Override protected void onResume()
{
super.onResume();
if (!unavez)
return;
for (int i=0; i<4; i++)
{
mList.addView(sec[i]);
//setContentView(sec[i]);
}
unavez = false;
}
#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;
}
}
When running, I can see the Button and the EditText in activity_main.xml, but I can't see my custom control in second.xml. If I use the line setContentView(sec[i]) instead of mList.addView(sec[i]) in onResume(), it gets worse: the EditText and the Button in activity_main.xml aren't visible and I get a blank layout.
How can I add my custom control to activity_main.xml and make it visible to user?
You elected to have Second inherit directly from ViewGroup. Since you did that, Second needs to be a real ViewGroup, with a real onLayout() implementation and everything else that goes along with being a ViewGroup. Do not just randomly override methods with do-nothing implementations, then complain when the do-nothing implementations do nothing.
Creating "custom controls" is a relatively advanced topic in Android. Newcomers to Android should focus on other solutions to whatever problem they think a "custom control" will somehow solve.