Dynamic Tablerow - inserting a textview contents in an existing tablerow - java

I'm creating my first android application, and want to use Dynamic Tablerow in my application. In my MainFragment.java, there is OnClickListener for adding text. I use Log.d to check whether it is working or not. I checked it work. But text is not added in Tablerow; its ID is mealRow.
I want add TextView in an existing Tablerow. Please check it and answer to me. Thanks.
I tried new Tablerow. But it also failed.
I mean new TextView in new Tablerow in an existing TableLayout.
MainFragment.java
public static MainFragment newInstance() {
return new MainFragment();
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.main_fragment, container, false);
Response.Listener<String> responseListener;
responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String mealList = response;
Log.d(TAG, mealList+"");
//TextView meal = (TextView) getView().findViewById(R.id.meal1);
//meal.setText(mealList);
}
};
Log.d(TAG, "Meal queued!");
MealRequest mealRequest = new MealRequest(countryCode, schulCode, insttNm, schulCrseScCode,
schMmealScCode, schYmd, responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(mealRequest);
Button create = (Button) view.findViewById(R.id.Create);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "button Clicked!");
TableRow mealRow = (TableRow) view.findViewById(R.id.mealRow);
ViewGroup.LayoutParams textParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView meals = new TextView(getActivity());
meals.setText("new");
meals.setLayoutParams(textParams);
meals.setGravity(Gravity.CENTER);
meals.setTextColor(Color.parseColor("#000000"));
meals.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
mealRow.addView(meals);
}
});
return view;
}
MainActivity.java
private final static String TAG = MainActivity.class.getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment_container, MainFragment.newInstance()).commit();
navigationView.setNavigationItemSelectedListener(this);
}
**--------------------------------cut--------------------------**
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, MainFragment.newInstance()).commit();
} else if (id == R.id.nav_calendar) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, Calendar.newInstance()).commit();
} else if (id == R.id.nav_timetable) {
} else if (id == R.id.nav_homework) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
main_fragment.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Today's meal"
android:textColor="#000000"
android:textSize="20sp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="#+id/mealTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:stretchColumns="*">
<TableRow
android:id="#+id/mealRow"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/meal1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginBottom="1dp"
android:gravity="center"
android:text="1"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:id="#+id/meal2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginBottom="1dp"
android:gravity="center"
android:text="2"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:id="#+id/meal3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginBottom="1dp"
android:gravity="center"
android:text="3"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:id="#+id/meal4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginBottom="1dp"
android:gravity="center"
android:text="4"
android:textColor="#000000"
android:textSize="20sp" />
</TableRow>
</TableLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:orientation="horizontal">
<Button
android:id="#+id/Create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Make Text!" />
</LinearLayout>
This is my expect :
Click 'Create' Button
new TextView is added in mealRow (Tablerow)
but the actual output is 'Nothing happened'.

You should use TableRow.LayoutParams than ViewGroup.LayoutParams.
This is because TextView goes into TableRow.
If TextView goes into RelativeLayout, you should use RelativeLayout.LayoutParams.

Related

Can the RecyclerView scroll with the rest of the fragment layouts?

I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}

View search Result in a new Activity

I have a search form on a fragment which works perfectly. At the moment I have a RecyclerView at the bottom of the form but I want it to load the search result on a new activity. Please help
layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="55dp"
android:orientation="vertical"
tools:context="com.ranake.rana.Search">
<!-- TODO: Update blank fragment layout -->
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/linearLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="vertical">
<EditText
android:id="#+id/search_field"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline2"
android:drawableLeft="#drawable/ic_make"
android:drawablePadding="10dp"
android:gravity="center_vertical"
android:hint="Make"
android:inputType="textPersonName"
android:padding="10dp"
android:textColorHint="#7f8c8d"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="7dp"
android:orientation="vertical">
<EditText
android:id="#+id/className"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline2"
android:drawableLeft="#drawable/ic_model"
android:drawablePadding="10dp"
android:gravity="center_vertical"
android:hint="Model"
android:inputType="text"
android:padding="10dp"
android:textColorHint="#7f8c8d"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="42dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#drawable/button_red_border"
android:text="Clear"
android:textColor="#color/colorPrimary" />
<Button
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="42dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="20dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#drawable/button_red"
android:text="Search"
android:textColor="#android:color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:layout_width="match_parent"
android:id="#+id/progressBar"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/result_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"></android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
Search.java:
public class Search extends Fragment {
private EditText mSearchField;
private Button mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Cars");
mSearchField = (EditText) view.findViewById(R.id.search_field);
mSearchBtn = (Button) view.findViewById(R.id.search_btn);
mResultList = (RecyclerView) view.findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setNestedScrollingEnabled(false);
mResultList.setLayoutManager(new LinearLayoutManager(getContext()));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
return view;
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(getActivity(), "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("title").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Cars, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cars, UsersViewHolder>(
Cars.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Cars model, int position) {
viewHolder.setDetails(getActivity().getApplicationContext(), model.getTitle(), model.getDesc(), model.getImage(), model.getMileage(), model.getTrans(), model.getFuel(), model.getPrice(), model.getLocation());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userTitle, String userDesc, String userImage, String userMileage, String userTrans, String userFuel, String userPrice, String userLocation){
TextView user_title = (TextView) mView.findViewById(R.id.name_text);
TextView user_desc = (TextView) mView.findViewById(R.id.status_text);
ImageView user_image = (ImageView) mView.findViewById(R.id.profile_image);
TextView user_mileage = (TextView) mView.findViewById(R.id.post_mileage);
TextView user_trans = (TextView) mView.findViewById(R.id.post_trans);
TextView user_fuel = (TextView) mView.findViewById(R.id.post_fuel);
TextView user_price = (TextView) mView.findViewById(R.id.post_price);
TextView user_location = (TextView) mView.findViewById(R.id.post_location);
user_title.setText(userTitle);
user_desc.setText(userDesc);
user_mileage.setText(userMileage);
user_trans.setText(userTrans);
user_fuel.setText(userFuel);
user_price.setText(userPrice);
user_location.setText(userLocation);
Glide.with(ctx).load(userImage).into(user_image);
}
}
When the search Button is clicked, I want it to open the new activity and load the results there.
You can pass this searchText to the next Activity (I'm calling it ResultsActivity) by passing it as an extra on the Intent:
private void firebaseUserSearch(String searchText) {
Intent intent = new Intent(getActivity(), ResultsActivity.class);
intent.putExtra("searchText",searchText);
startActivity(intent);
}
Then receive it on the other Activity using Intent.getExtras():
String searchText = getIntent().getExtras().getString("searchText");
And finally populate the RecyclerView from that Activity:
Query firebaseSearchQuery = mUserDatabase.orderByChild("title").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Cars, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cars, UsersViewHolder>(
Cars.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Cars model, int position) {
viewHolder.setDetails(getActivity().getApplicationContext(), model.getTitle(), model.getDesc(), model.getImage(), model.getMileage(), model.getTrans(), model.getFuel(), model.getPrice(), model.getLocation());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);

how to set text to text view based on the selection of item in dialogfragment and value of text in main activity, is it possible?

Here I am trying to set text to a textview in my activity.
The text is set to the text view based on the text of the text view in my activity and the selected item in the custom dialog fragment.
The dialog fragment consists of recycler view and a button.when item is selected from the fragment and text of textview of my activity, and with both cases settext to the textview. I tried different code but I not getting how to achieve it anyone give me solution for it. is there a way to get it.
by using value of text and selected item, adding my math and condition to it. settext to the textview. I am beginner to coding can any one help me please I'm trying from 5 days to achieve it. please help me thanks in advance
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="YOUR DAILY TARGET"
android:layout_gravity="center"
android:id="#+id/textView7"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_gravity="center"
android:id="#+id/res"
android:layout_marginTop="20dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Select a glass"
android:layout_marginLeft="10dp"
android:id="#+id/textView6"
android:layout_gravity="center" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:src="#android:drawable/ic_input_add" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="70dp"
android:layout_height="70dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="0"
android:background="#drawable/circle"
android:gravity="center"
android:id="#+id/glasses"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="31dp"
android:layout_marginEnd="31dp"
android:layout_marginBottom="121dp" />
</RelativeLayout>
</LinearLayout>
MainActivity:
public class MainActivity extends AppCompatActivity {
private Listen selectedListen;
protected void setDataFromMyDialog(Listen listen) {
this.selectedListen = listen;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, Page.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
TextView textView = (TextView)findViewById(R.id.res);
Intent r = getIntent();
double res = r.getDoubleExtra("res", 0);
textView.setText(+res + "L"); // with this text value
double ram = Double.parseDouble(textView.getText().toString());
TextView gls = (TextView) findViewById(R.id.glasses);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DiaFragment df = new DiaFragment();
df.show(MainActivity.this.getSupportFragmentManager(), "Frag");
}
});
}
with the text of textview above and selected item in my dialog fragment by using both the values the set text of TextView glasses.is it possible to get like this
DiaFrag:
public class DiaFragment extends DialogFragment {
ListAdapter listAdapter;
public DiaFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
setCancelable(false);
Button ok = (Button) v.findViewById(R.id.submit);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.list);
listAdapter = new ListAdapter(getContext(),getData());
recyclerView.setAdapter(listAdapter);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setDataFromMyDialog(listAdapter.getSelectedData());
dismiss();
}
});
return v;
}
public static List<Listen> getData()
{
List<Listen> data = new ArrayList<>();
int[] images = {R.drawable.bottle,R.drawable.lotion,R.drawable.soap,R.drawable.soda,R.drawable.sodaa};
String[] texts = {"250ml","300ml","500ml","750ml","1ltr"};
for (int i=0;i<texts.length && i<images.length;i++){
Listen current = new Listen();
current.img = images[i];
current.text= texts[i];
data.add(current);
}
return data;
}
}

using layout file for fragment in Navigation drawer layout

I have an android app code that uses the navigation drawer layout with fragments as the main content.
So far I have had a specific fragment class for all the fragment items in my drawer. Now I do however have a different layout I want to get as an item in my drawer as well. The layout is a LiniarLayout and defined in xml characteristic.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_device_address"
android:textSize="18sp"/>
<Space android:layout_width="5dp"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/device_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_state"
android:textSize="18sp"/>
<Space android:layout_width="5dp"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/connection_state"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/disconnected"
android:textSize="18sp"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_data"
android:textSize="18sp"/>
<Space android:layout_width="5dp"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/data_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/no_data"
android:textSize="18sp"/>
</LinearLayout>
<ExpandableListView android:id="#+id/gatt_services_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
in my main activity I preload the fragments in the onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create adapters early
mAdapter = new DeviceAdapter(this, false);
mFilterAdapter = new DeviceAdapter(this, true);
setContentView(R.layout.activity_main);
mFragmentManager = getFragmentManager();
mNavigationDrawerFragment = (NavigationDrawerFragment)
mFragmentManager.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
mDevices = new HashMap<String, ScanResultContent.BtLeDeviceItem>();
mFilteredDevices = new HashMap<String, ScanResultContent.BtLeDeviceItem>();
//setup fragment 1
mScanResultFragment = new ResultListFragment();
//setup fragment 2
mFilteredScanResultFragment = new ResultListFragment();
mScanResultFragment.setListAdapter(mAdapter);
//setup fragment 3
mDeviceInfoFragment = DeviceInfoFragment.newInstance("");
// Sets up UI references for the Device Info viewer.
mConnectionState = (TextView) findViewById(R.id.connection_state);
mDataField = (TextView) findViewById(R.id.data_value);
mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list);
mGattServicesList.setOnChildClickListener(servicesListClickListner);
mFilteredScanResultFragment.setListAdapter(mFilterAdapter);
// setup default fragment shown
mFragmentManager.beginTransaction().add(R.id.container, mScanResultFragment).commit();
}
I have tried to get the layout loaded into a fragment using the DeviceInfoFragment class:
public class DeviceInfoFragment extends Fragment {
public DeviceInfoFragment(){
super();
}
public static DeviceInfoFragment newInstance(String text) {
DeviceInfoFragment f = new DeviceInfoFragment();
Bundle b = new Bundle();
b.putString("text", text);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gatt_characteristics_layout, container, false);
return v;
}
}
I want to be able to switch between the fragments using this (which have worked fine except for the new fragment 3):
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment f = null;
switch (position+1){
case 1:
f = mScanResultFragment;
mTitle = getString(R.string.title_devicescan);
break;
case 2:
f = mFilteredScanResultFragment;
mTitle = getString(R.string.title_results);
break;
case 3:
f = mDeviceInfoFragment;
mTitle = getString(R.string.title_device_info);
break;
}
if(f != null) {
mFragmentManager.beginTransaction()
.replace(R.id.container, f)
.commit();
}
restoreActionBar();
}
It does however not seem to work as the line:
mGattServicesList.setOnChildClickListener(servicesListClickListner);
fails with
E/AndroidRuntime(30644): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ExpandableListView.setOnChildClickListener(android.widget.ExpandableListView$OnChildClickListener)' on a null object reference
Can anyone tell me what I am doing wrong here?

Cant get button onclicklistener to work with listview

I have a list view that is clickable along with a button in it that is also clickable. Problem is I cant get the button to do anything ( it shows the click/highlight but my action isnt performed ).
here is my Photo.class:
public class Photos extends MyBaseMenuOptions implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
LayoutInflater inflater = Photos.this.getLayoutInflater();
final View buttonView = inflater.inflate(R.layout.list_item, null);
Button button = (Button) buttonView.findViewById(R.id.trash);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
});
...
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
I also have a #Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) { in the class but that works when you click the listview
Here is my list_item.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" >
<ImageView
android:id="#+id/icon"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/image"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
<Button
android:id="#+id/trash"
android:layout_width="70dp"
android:layout_height="70dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_alignParentRight="true"
android:focusable="false"
android:descendantFocusability="blocksDescendants"
/>
</RelativeLayout>
so i had same problem
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/beam_contact_entry_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/sv_standard_padding"
android:paddingRight="25dp"
android:background="?entry_background" >
<TextView
android:id="#+id/beam_contact_fragment_top_letter"
style="?primary_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?entry_background"
android:visibility="gone"
android:text="A"
android:textColor="#color/black" />
<include
android:id="#+id/beam_contact_fragment_top_line_fit"
android:layout_width="fill_parent"
android:layout_height="#dimen/sv_stripe_height_for_header"
android:layout_below="#+id/beam_contact_fragment_top_letter"
android:visibility="gone"
layout="#layout/svyaznoy_stripe" />
<FrameLayout
android:id="#+id/beam_contact_fragment_top_line_slim"
android:layout_width="match_parent"
android:layout_height="0.25dp"
android:layout_below="#+id/beam_contact_fragment_top_line_fit"
android:visibility="gone"
android:background="?divider_background" >
</FrameLayout>
<RelativeLayout
android:id="#+id/beam_contact_entry_contact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/sv_standard_padding"
android:paddingBottom="#dimen/sv_standard_padding"
android:layout_alignParentLeft="true"
android:layout_below="#+id/beam_contact_fragment_top_line_slim"
android:layout_toLeftOf="#+id/beam_contact_entry_invite"
android:background="?entry_background" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:orientation="vertical"
android:layout_toRightOf="#+id/contact_info_avatar" >
<TextView
android:id="#+id/beam_contact_fragment_entry_text"
style="?primary_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alexander Great"
android:textSize="18sp" />
<TextView
android:id="#+id/beam_contact_fragment_entry_text_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="-4dp"
android:text="mobile"
android:visibility="gone"
style="?secondary_text"
android:textSize="15sp" />
</LinearLayout>
<ru.fon.svyaznoy.ui.UserpicImageView
android:id="#+id/contact_info_avatar"
android:layout_width="#dimen/avatar_picture_side"
android:layout_height="#dimen/avatar_picture_side"
android:layout_alignParentLeft="true"
android:src="#drawable/sv_no_userpic" />
</RelativeLayout>
<LinearLayout
android:id="#+id/beam_contact_entry_invite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/beam_contact_entry_contact"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/beam_contact_entry_contact"
android:background="?entry_background"
android:orientation="horizontal" >
<ImageView
android:id="#+id/beam_contact_fragment_entry_right_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="?entry_background"
android:duplicateParentState="true"
android:src="#drawable/sv_svyaznoy_contact" />
</LinearLayout>
</RelativeLayout>
in adapter in method getView
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
View childview1 = view.findViewById(R.id.beam_contact_entry_contact)
childview1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// your text
}
});
View childview2 = view.findViewById(R.id.beam_contact_entry_invite);
childview2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// your text 2
}
});
return view;
}
I think you should set the onClickListener on the button within the adapter.
Something like that :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//fill your cell
Button button = (Button) buttonView.findViewById(R.id.trash);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
});
}
you have to write click event for button in the adapter.
write the click event for button in the get view method of adapter and there only you will get the button instance.
good luck
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflator inflater = LayoutInflator.from(context);
if(convertview == null {
convertview = inflater .inflate(R.layout.listitem, parent, false);
}
Button button = (Button) convertView.findViewById(R.id.trash);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
});
return convertview;
May this works fine
good luck

Categories