android.view.IflateException:Binary XML file #1: Error inflating class - java

activity_test_sliding_menu.xml
<com.hpc.cbs.myapplication.FlyOutContainer xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#444488"
android:orientation="vertical"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="toggleMenu"
android:text="Button 1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="toggleMenu"
android:text="Button 1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="toggleMenu"
android:text="Button 1"/>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#888888"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bla bla"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="toggleMenu"
android:text="toggle"/>
</LinearLayout>
</com.hpc.cbs.myapplication.FlyOutContainer>
and here is class
FlyOutContainer.class
public class FlyOutContainer extends LinearLayout {
private View menu;
private View content;
//Constants
protected static final int menuMargin = 150;
protected enum MenuState {
CLOSED, OPEN, CLOSING, OPENING
};
//position information attributes
protected int currentContentOffset = 0;
protected MenuState menuCurrentState = MenuState.CLOSED;
//Animation objects
protected Scroller menuAnimationScroller = new Scroller(this.getContext(), new LinearInterpolator());
protected Runnable menuAnimationRunnable = new AnimationRunnable();
protected Handler menuAnimationHandler = new Handler();
//animation constants
private static final int menuAnimationDuration = 1000;
private static final int menuAnimationPollingInterval = 16;
public FlyOutContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public FlyOutContainer(Context context){
super(context);
}
protected void onAttachedToWindow(){
super.onAttachedToWindow();
this.menu = this.getChildAt(0);
this.content = this.getChildAt(1);
this.menu.setVisibility(View.GONE);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
if(changed)
this.calculateChildDimension();
this.menu.layout(left, top, right-menuMargin, bottom);
this.content.layout(left + this.currentContentOffset, top, right + this.currentContentOffset, bottom);
}
public void toggleMenu() {
switch (this.menuCurrentState) {
case CLOSED:
this.menu.setVisibility(View.VISIBLE);
this.currentContentOffset = this.getMenuWidth();
this.content.offsetLeftAndRight(currentContentOffset);
this.menuCurrentState = MenuState.OPEN;
break;
case OPEN:
this.menu.setVisibility(View.GONE);
this.currentContentOffset = 0;
this.content.offsetLeftAndRight(-currentContentOffset);
this.menuCurrentState = MenuState.CLOSED;
break;
default:
return;
}
this.menuAnimationHandler .postDelayed(this.menuAnimationRunnable, menuAnimationPollingInterval);
}
private int getMenuWidth() {
return this.menu.getLayoutParams().width;
}
private void calculateChildDimension(){
this.content.getLayoutParams().height = this.getHeight();
this.content.getLayoutParams().width = this.getWidth();
this.menu.getLayoutParams().width = this.getWidth() - menuMargin;
this.menu.getLayoutParams().height = this.getHeight();
}
private void adjustContentPosition(boolean isAnimationOngoing)
{
int scrollerOffset = this.menuAnimationScroller.getCurrX();
this.content.offsetLeftAndRight(scrollerOffset - this.currentContentOffset);
this.currentContentOffset = scrollerOffset;
this.invalidate();
if(isAnimationOngoing)
this.menuAnimationHandler.postDelayed(this.menuAnimationRunnable, menuAnimationPollingInterval);
else
this.onMenuTransitionComplete();
}
private void onMenuTransitionComplete()
{
switch (this.menuCurrentState)
{
case OPENING:
this.menuCurrentState = MenuState.OPEN;
break;
case CLOSING:
this.menuCurrentState = MenuState.CLOSED;
this.menu.setVisibility(View.GONE);
break;
default:
return;
}
}
protected class SmoothInterpolator implements Interpolator {
#Override
public float getInterpolation(float t)
{
return (float) Math.pow(t-1,5) + 1;
}
}
protected class AnimationRunnable implements Runnable
{
#Override
public void run()
{
boolean isAnimationOngoing = FlyOutContainer.this.menuAnimationScroller.computeScrollOffset();
FlyOutContainer.this.adjustContentPosition(isAnimationOngoing);
}
}
}
here is TestSlidingMenuActivity.java
public class TestSlidingMenuActivity extends Activity {
FlyOutContainer root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.root = (FlyOutContainer) this.getLayoutInflater().inflate(R.layout.activity_test_sliding_menu, null);
setContentView(root);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sample, menu);
return true;
}
public void toggleMenu(View v)
{
this.root.toggleMenu();
}
}
How can I fix this?

Related

java.lang.IllegalStateException: Required view 'caption' with ID 2131230791 for field 'caption' was not found

I created a custom view VerticalTextView which is as given below.
public class VerticalTextView extends AppCompatTextView {
private boolean isVerticalText = false;
private boolean topDown = false;
public VerticalTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (attrs != null) {
TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.VerticalTextView);
isVerticalText = array.getBoolean(R.styleable.VerticalTextView_is_vertical_text, false);
topDown = array.getBoolean(R.styleable.VerticalTextView_top_down, false);
array.recycle();
}
}
public VerticalTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public VerticalTextView(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// vise versa
if (isVerticalText) {
int height = getMeasuredWidth();
int width = getMeasuredHeight();
setMeasuredDimension(width, height);
}
}
public void setVerticalText(boolean verticalText) {
isVerticalText = verticalText;
}
#Override
protected void onDraw(Canvas canvas) {
if (isVerticalText) {
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
canvas.save();
if (topDown) {
canvas.translate(getWidth(), 0);
canvas.rotate(90);
} else {
canvas.translate(0, getHeight());
canvas.rotate(-90);
}
canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
getLayout().draw(canvas);
canvas.restore();
} else {
super.onDraw(canvas);
}
}
}
Then I used it in LogInFragment as shown below:
login_fragment.xml
<androidx.constraintlayout.widget.ConstraintLayout 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:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:background="#color/color_sign_up">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="48dp" />
<View
android:id="#+id/logo"
android:layout_width="#dimen/logo_size"
android:layout_height="#dimen/logo_size"
android:layout_marginTop="8dp"
android:focusable="true"
android:focusableInTouchMode="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/email_input"
style="#style/Widget.TextInputLayout"
android:layout_marginTop="48dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/logo">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/email_input_edit"
style="#style/Widget.TextEdit"
android:hint="#string/email_hint"
android:inputType="textEmailAddress" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/password_input"
style="#style/Widget.TextInputLayout"
android:layout_marginTop="16dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email_input"
app:passwordToggleTint="#color/color_input_hint">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/password_input_edit"
style="#style/Widget.TextEdit"
android:hint="#string/password_hint"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:gravity="center"
android:text="#string/forgot_password"
android:textColor="#FFF"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/password_input" />
<com.learn.fsrsolution.models.VerticalTextView
android:id="#+id/caption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/log_in_label"
android:textAllCaps="true"
android:textColor="#color/color_label"
android:textSize="#dimen/unfolded_size"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.78" />
</androidx.constraintlayout.widget.ConstraintLayout>
LogInFragment.java
public class LogInFragment extends AuthFragment {
#BindViews(value = {R.id.email_input_edit, R.id.password_input_edit})
protected List<TextInputEditText> views;
#BindView(R.id.password_input)
TextInputLayout inputLayout;
#BindView(R.id.caption)
VerticalTextView caption;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
caption.setText(getString(R.string.log_in_label));
view.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.color_log_in));
for (TextInputEditText editText : views) {
if (editText.getId() == R.id.password_input_edit) {
ButterKnife.bind(this, inputLayout);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
inputLayout.setTypeface(boldTypeface);
editText.addTextChangedListener(new TextWatcherAdapter() {
#Override
public void afterTextChanged(Editable editable) {
inputLayout.setPasswordVisibilityToggleEnabled(editable.length() > 0);
}
});
}
editText.setOnFocusChangeListener((temp, hasFocus) -> {
if (!hasFocus) {
boolean isEnabled = editText.getText().length() > 0;
editText.setSelected(isEnabled);
}
});
}
}
#Override
public int authLayout() {
return R.layout.login_fragment;
}
#Override
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void fold() {
lock = false;
Rotate transition = new Rotate();
transition.setEndAngle(-90f);
transition.addTarget(caption);
TransitionSet set = new TransitionSet();
set.setDuration(getResources().getInteger(R.integer.duration));
ChangeBounds changeBounds = new ChangeBounds();
set.addTransition(changeBounds);
set.addTransition(transition);
TextSizeTransition sizeTransition = new TextSizeTransition();
sizeTransition.addTarget(caption);
set.addTransition(sizeTransition);
set.setOrdering(TransitionSet.ORDERING_TOGETHER);
final float padding = getResources().getDimension(R.dimen.folded_label_padding) / 2;
set.addListener(new Transition.TransitionListenerAdapter() {
#Override
public void onTransitionEnd(Transition transition) {
super.onTransitionEnd(transition);
caption.setTranslationX(-padding);
caption.setRotation(0);
caption.setVerticalText(true);
caption.requestLayout();
}
});
TransitionManager.beginDelayedTransition(parent, set);
caption.setTextSize(TypedValue.COMPLEX_UNIT_PX, caption.getTextSize() / 2);
caption.setTextColor(Color.WHITE);
ConstraintLayout.LayoutParams params = getParams();
params.leftToLeft = ConstraintLayout.LayoutParams.UNSET;
params.verticalBias = 0.5f;
caption.setLayoutParams(params);
caption.setTranslationX((caption.getWidth() / 8) - padding);
}
#Override
public void clearFocus() {
for (View view : views) view.clearFocus();
}
}
Then I used caption in AuthFragment as follows.
public abstract class AuthFragment extends Fragment {
protected Callback callback;
#BindView(R.id.caption)
protected VerticalTextView caption;
#BindView(R.id.root)
protected ViewGroup parent;
protected boolean lock;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(authLayout(), container, false);
ButterKnife.bind(this, root);
KeyboardVisibilityEvent.setEventListener(getActivity(), isOpen -> {
callback.scale(isOpen);
if (!isOpen) {
clearFocus();
}
});
return root;
}
public void setCallback(#NonNull Callback callback) {
this.callback = callback;
}
#LayoutRes
public abstract int authLayout();
public abstract void fold();
public abstract void clearFocus();
#OnClick(R.id.root)
public void unfold() {
if (!lock) {
caption.setVerticalText(false);
caption.requestLayout();
Rotate transition = new Rotate();
transition.setStartAngle(-90f);
transition.setEndAngle(0f);
transition.addTarget(caption);
TransitionSet set = new TransitionSet();
set.setDuration(getResources().getInteger(R.integer.duration));
ChangeBounds changeBounds = new ChangeBounds();
set.addTransition(changeBounds);
set.addTransition(transition);
TextSizeTransition sizeTransition = new TextSizeTransition();
sizeTransition.addTarget(caption);
set.addTransition(sizeTransition);
set.setOrdering(TransitionSet.ORDERING_TOGETHER);
caption.post(() -> {
TransitionManager.beginDelayedTransition(parent, set);
caption.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.unfolded_size));
caption.setTextColor(ContextCompat.getColor(getContext(), R.color.color_label));
caption.setTranslationX(0);
ConstraintLayout.LayoutParams params = getParams();
params.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
params.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
params.verticalBias = 0.78f;
caption.setLayoutParams(params);
});
callback.show(this);
lock = true;
}
}
protected ConstraintLayout.LayoutParams getParams() {
return (ConstraintLayout.LayoutParams) caption.getLayoutParams();
}
public interface Callback {
void show(AuthFragment fragment);
void scale(boolean hasFocus);
}
}
When I run that code, I get below error:
java.lang.IllegalStateException: Required view 'caption' with ID 2131230791 for field 'caption' was not found.
How can I fix it?
Sometimes butter knife doesn't work with Custom views. So try to do it manually too.
But here, why are you declaring caption property again in Login Fragment?
(#BindView(R.id.caption) VerticalTextView caption;)
AuthFragment is abstract and you are passing layout id to it from child fragment.
Then why you created another property of VerticalTextView caption; in child class too when it is already in parent class.

Android RecyclerView EndlessScroll ProgressBar?

I'm trying to add ProgressBar to the bottom of the list while loading next page. How can do it? Is there a way to place my progressbar more efficiently? I saw many uses viewtype in adapter, but i don't really get how it changes. Also, after progressbar ended and new page added, i want the bottom item to scroll for 1 position below.
This is my list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:orientation="vertical"
android:divider="#android:color/black">
<TextView
android:id="#+id/id"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"/>
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"/>
<TextView
android:id="#+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="10dp"/>
</LinearLayout>
<ProgressBar
android:visibility="gone"
android:id="#+id/progressbar"
android:progress="1"
android:layout_width="100dp"
android:layout_height="100dp"
android:indeterminate="true"
android:layout_gravity="center_horizontal"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#ccc"/>
</android.support.v7.widget.CardView>
This is my MyAdapter.java
import android.app.Activity;
import android.content.Context;
import android.service.autofill.Dataset;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import java.util.ArrayList;
import java.util.HashMap;
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
Context c;
ArrayList<String> id;
ArrayList<String> name;
ArrayList<String> email;
ArrayList<String> phone;
private Activity mactivity;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private boolean isLoading;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private OnLoadMoreListener onLoadMoreListener;
public interface OnLoadMoreListener {
void onLoadMore();
}
public MyAdapter(Context c, ArrayList<String> id, ArrayList<String> name, ArrayList<String> email, ArrayList<String> phone) {
this.c = c;
this.id = id;
this.name = name;
this.email= email;
this.phone = phone;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d("viewType", "onCreateViewHolder: "+viewType);
View v = LayoutInflater.from(c).inflate(R.layout.list_item, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.id.setText(id.get(position));
holder.name.setText(name.get(position));
holder.email.setText(email.get(position));
holder.phone.setText(phone.get(position));
}
#Override
public int getItemCount() {
return id.size();
}
}
This is my MainActivity.java
public class MainActivity extends AppCompatActivity {
private String URL = "myURL.php";
private String token = "mytoken";
RecyclerView mrecyclerView;
MyAdapter myAdapter;
ArrayList<String> id = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
ArrayList<String> email = new ArrayList<>();
ArrayList<String> phone = new ArrayList<>();
String next_page="";
ProgressBar mProgressBar;
private Parcelable recyclerViewState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar =(ProgressBar)findViewById(R.id.progressbar);
mrecyclerView = (RecyclerView) findViewById(R.id.mRecyclerview);
mrecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false));
new getJSON().execute();
myAdapter = new MyAdapter(getApplicationContext(), id, name, email, phone);
mrecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
#Override
public void onLoadMore() {
if (URL != null) {
//mProgressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
recyclerViewState = mrecyclerView.getLayoutManager().onSaveInstanceState();
URL = next_page;
new getJSON().execute();
}
}, 200);
//mProgressBar.setVisibility(View.GONE);
}
}
});
}
private class getJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void v) {
super.onPostExecute(v);
mrecyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
mrecyclerView.setAdapter(myAdapter);
}
#Override
protected Void doInBackground(Void... voids) {
HTTPHandler httpHandler = new HTTPHandler();
String json = httpHandler.makeCall(URL, token);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("data");
next_page = String.valueOf(jsonObject.get("next_page_url"));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
id.add(obj.getString("id"));
name.add(obj.getString("name"));
email.add(obj.getString("email"));
phone.add(obj.getString("phone"));
}
} catch (final JSONException e) {
Log.e("ERROR", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e("ERROR", "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
}
}
and i used EndlessRecyclerOnScrollListener.java from here
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
// public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
/**
* The total number of items in the dataset after the last load
*/
private int mPreviousTotal=0;
/**
* True if we are still waiting for the last set of data to load.
*/
private boolean mLoading = true;
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = recyclerView.getChildCount();
int totalItemCount = recyclerView.getLayoutManager().getItemCount();
int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
}
}
int visibleThreshold = 5;
if (!mLoading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
onLoadMore();
mLoading = true;
}
}
public abstract void onLoadMore();
}
This progressbar should be added in your activity's xml and not in list_item.xml but it is not.
So with this line in your activity class:
mProgressBar =(ProgressBar)findViewById(R.id.progressbar);
the variable mProgressBar is null because it cannot be found inside the activity's xml.
So move the below code from list_item.xml to activity_main.xml:
<ProgressBar
android:visibility="gone"
android:id="#+id/progressbar"
android:progress="1"
android:layout_width="100dp"
android:layout_height="100dp"
android:indeterminate="true"
android:layout_gravity="center_horizontal"/>

RecyclerView Android Dynamic Height

I am looking at creating dynamic heights in my RecyclerView to be responsive across all devices. Currently this works fine but for the first two rows at the start I have a double cell and the height of these two rows gets set to the first cell. I want instead this cell on both the first and second row to match the height of the last cell and become a rectangle. I have tried a few ways but none seem to work I am not sure where the problem is but I hope someone can show me. I will attach screenshots and the code below.
SquareLayout.java
public class SquareLayout extends LinearLayout {
public SquareLayout(Context context) {
super(context);
}
public SquareLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int width, int height) {
// int width = MeasureSpec.getSize(widthMeasureSpec);
//int height = MeasureSpec.getSize(heightMeasureSpec);
// note we are applying the width value as the height
//if(width>=370){
// super.onMeasure(widthMeasureSpec, widthMeasureSpec/2);
// }
// else{
// super.onMeasure(widthMeasureSpec, widthMeasureSpec);
// }
super.onMeasure(width, width);
// Log.d("int","int is: "+ width);
}
}
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<AndroidVersion> android;
private Context context;
public DataAdapter(Context context,ArrayList<AndroidVersion> android) {
this.android = android;
this.context = context;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
// int width = viewHolder.tv_android.getMeasuredWidth() / 2; //returns -1
Log.d("MYINT", "value: " + i);
//Picasso.with(context).load(android.get(i).getAndroid_image_url()).resize(240, 120).into(viewHolder.img_android);
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private LinearLayout testheight;
private ImageView img_android;
public ViewHolder(View view) {
super(view);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private final String android_version_names[] = {
"test1",
"test2",
"test3",
"test4",
"test5",
"test6",
"test7",
"test8",
"test9",
"test10"
};
private final String android_image_urls[] = {
"http://example.com/images/test.png",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(),3);
ArrayList<AndroidVersion> androidVersions = prepareData();
((GridLayoutManager) mLayoutManager).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
if (position == 0 || position == 2) {
return 2; // ITEMS AT POSITION 1 AND 6 OCCUPY 3 SPACES
}
else {
return 1; // OTHER ITEMS OCCUPY ONLY A SINGLE SPACE
}
}
});
recyclerView.setLayoutManager(mLayoutManager);
DataAdapter adapter = new DataAdapter(getApplicationContext(), androidVersions);
recyclerView.setAdapter(adapter);
}
private ArrayList<AndroidVersion> prepareData(){
ArrayList<AndroidVersion> android_version = new ArrayList<>();
for(int i=0;i<android_version_names.length;i++){
AndroidVersion androidVersion = new AndroidVersion();
androidVersion.setAndroid_version_name(android_version_names[i]);
androidVersion.setAndroid_image_url(android_image_urls[i]);
android_version.add(androidVersion);
}
return android_version;
}
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<example.SquareLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:layout_marginStart="10dp"
android:background="#color/reloadedpurple"
android:elevation="6dp"
android:orientation="vertical">
<ImageView
android:id="#+id/img_android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
<TextView
android:id="#+id/tv_android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:textColor="#FFFFFF"
android:textStyle="bold" />
</LinearLayout>
</example.SquareLayout>

Dynamically Setting a Fixed Height for a Staggered Grid View

I'm trying to take a RecyclerView with a StaggeredGridLayout and make it a fixed height by having it measure the views and set the height dynamically. I'm overriding the onMeasure(), but it does not always seem to measure correctly. I'd say it works about 50% of the time. The other 50% of the time it under measures it. I think it has to do with when the text wraps in the view_tile_small.xml, but I'm not sure.
Fragment
public class AtTheMuseumFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
//Odds n Ends Variables
private MapFragment mapFragment;
private FragmentTransaction fragmentTransaction;
private User user = new User();
private MuseumCollection museumCollection;
private Context context;
//Story Grid Adapter Variables
private AtTheMuseumAdapter nearMeAdapter;
private TileFactory tileFactory;
//Interfaces
private OnFragmentChangeListener changeListener;
#Bind(R.id.stories_list_view) RecyclerView storiesListView;
#Bind(R.id.swipe_container) SwipeRefreshLayout swipeRefreshLayout;
public static AtTheMuseumFragment newInstance(MuseumCollection museumCollection) {
AtTheMuseumFragment fragment = new AtTheMuseumFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public AtTheMuseumFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
museumCollection = ((MainActivity) getActivity()).getMuseumCollection();
context = getActivity().getApplicationContext();
tileFactory = new TileFactory();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_museum, container, false);
ButterKnife.bind(this, view);
//Sets up the layoutManager to the Mason View
storiesListView.setLayoutManager(new MeasuredStaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
//Sets up The map
try{
fragmentTransaction = getChildFragmentManager().beginTransaction();
mapFragment = MapFragment.newInstance(MapFragment.MUSEUM);
fragmentTransaction.add(R.id.museum_map, mapFragment).commit();
}catch (Exception e){
Log.d("Map - Initial Inflate:", e.getMessage());
}
//Sets up the swipe to refresh jawn
swipeRefreshLayout.setOnRefreshListener(this);
setNearMeAdapter();
return view;
}
#Override
public void onResume(){
super.onResume();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
changeListener = (OnFragmentChangeListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
changeListener = null;
}
/**
* Loads the adapter once the data is ready
*
*/
public void setNearMeAdapter(){
List<MuseumObject> newList = museumCollection.getObjectsNearUser(User.position, 4);
List<Tile> tiles = tileFactory.createAtMuseumFeed(newList, true);
nearMeAdapter = new AtTheMuseumAdapter(context, tiles, getActivity());
storiesListView.setAdapter(nearMeAdapter);
}
/**
* Refreshes Adapter with new data
*
*/
public void refreshNearMeAdapter(){
//TODO CHANGE THIS TO LOCATION BASED WHEN TIME IS RIGHT - Peter
//nearMeAdapter.setNewData(MuseumCollection.getObjectsNearUser(User.position, 4));
List<MuseumObject> newList = museumCollection.getRandomOrder();
nearMeAdapter.setNewData(tileFactory.createAtMuseumFeed(newList,false));
}
/**
* Adds past data to the Adapter
*
*/
public void loadPastObjects(){
//TODO MAKE THIS NOT ONLY LOAD RANDOM DATA - Peter
List<MuseumObject> newList = museumCollection.getRandomOrder();
nearMeAdapter.addNewData(tileFactory.createAtMuseumFeed(newList, false));
nearMeAdapter.notifyDataSetChanged();
}
#Override
public void onRefresh() {
user.updateUserLocation();
refreshNearMeAdapter();
mapFragment.refreshMap(museumCollection.getObjectFeed());
swipeRefreshLayout.setRefreshing(false);
}
public interface OnFragmentChangeListener {
void onFragmentChange(String fragment);
}
#OnClick(R.id.explore_map)
public void exploreMap(){
changeListener.onFragmentChange("map");
}
#OnClick(R.id.load_more)
public void loadMore(){
loadPastObjects();
}
}
MeasuredStaggeredGridLayoutManager
public class MeasuredStaggeredGridLayoutManager extends StaggeredGridLayoutManager {
public MeasuredStaggeredGridLayoutManager(int spanCount, int orientation) {
super(spanCount, orientation);
}
private int[] mMeasuredDimension = new int[2];
#Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
int heightR = 0;
int heightL = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
if(i % 2 == 0){
heightL += mMeasuredDimension[1];
}else{
heightR += mMeasuredDimension[1];
}
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
if(heightL != 0 || heightR != 0){
height = (heightL > heightR) ? heightL : heightR;
}
//TODO come up with a better way to fix the slightly wrong height
// must be not accounting for padding or margin or something - Peter
height += (20 * (getItemCount() / 2)) + 5;
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
AtTheMuseumAdapter
public class AtTheMuseumAdapter extends RecyclerView.Adapter<AtTheMuseumAdapter.MuseumStoriesViewHolder> {
private List<Tile> tiles;
private LayoutInflater inflater;
private AdapterCallback mListener;
private Context context;
public AtTheMuseumAdapter(Context context, List<Tile> tiles, Activity activity) {
this.tiles = tiles;
this.context = context;
inflater = LayoutInflater.from(this.context);
//Sets up interface between Stock Adapter and Fragment
try {
this.mListener = ((AdapterCallback) activity);
} catch (ClassCastException e) {
throw new ClassCastException("Fragment must implement AdapterCallback.");
}
}
#Override
public MuseumStoriesViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = inflater.inflate(R.layout.view_tile_small, viewGroup, false);
MuseumStoriesViewHolder holder = new MuseumStoriesViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MuseumStoriesViewHolder holder, int position) {
Tile currentTile = tiles.get(position);
holder.title.setText(currentTile.getTitle());
holder.desc.setText(currentTile.getDescription());
holder.type.setText(currentTile.getObjectTypeName());
//Using Picasso since it handles caching and all that jazz
Picasso.with(context)
.load(currentTile.getImg())
.into(holder.img);
}
#Override
public int getItemCount() {
return tiles.size();
}
public void setNewData(List<Tile> newItems){
tiles = newItems;
notifyDataSetChanged();
}
public void addNewData(final List<Tile> newItems){
tiles.addAll(newItems);
notifyDataSetChanged();
}
class MuseumStoriesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView type,title,desc;
public ImageView img;
public MuseumStoriesViewHolder(View itemView) {
super(itemView);
//Tried Butterknife, but it doesn't seem like it was working in the view holder. - Peter
type = (TextView) itemView.findViewById(R.id.small_box_type);
title = (TextView) itemView.findViewById(R.id.small_box_title);
desc = (TextView) itemView.findViewById(R.id.small_box_desc);
img = (ImageView) itemView.findViewById(R.id.small_box_image);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Tile t = tiles.get(getPosition());
switch (t.getObjectTypeName()){
case Tile.OBJECT_NAME:
mListener.onObjectClick(t.getObjectID());
break;
case Tile.TOUR_NAME:
mListener.onTourCLick(t.getTourID());
break;
case Tile.STORY_NAME:
mListener.onStoryClick(t.getObjectID(), t.getStoryID());
break;
}
}
}
public interface AdapterCallback {
public void onObjectClick(String objectID);
public void onStoryClick(String objectID, String storyID);
public void onTourCLick(String tourID);
}
}
view_tile_small.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin_small"
android:background="#color/small_box_background_color">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--TODO Make layout_height wrap contenet -->
<ImageView
android:id="#+id/small_box_image"
android:layout_width="match_parent"
android:layout_height="150dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:maxHeight="150dp"
android:background="#color/transparent"/>
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="right"
android:src="#drawable/abc_btn_rating_star_off_mtrl_alpha"
/>
<TextView
android:id="#+id/small_box_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/margin_normal"
android:paddingBottom="#dimen/margin_normal"
android:textSize="#dimen/font_small"
android:textColor="#color/font_white"
android:background="#drawable/small_box_text_bottom_border"
android:layout_gravity="bottom"
android:text="Object Story"
/>
</FrameLayout>
<TextView
android:id="#+id/small_box_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin_larger"
android:layout_marginBottom="#dimen/margin_normal"
android:layout_marginRight="#dimen/margin_larger"
android:layout_marginTop="#dimen/margin_larger"
android:textSize="#dimen/font_large"
android:textColor="#color/font_black"
android:text="Sample Text Here"
/>
<TextView
android:id="#+id/small_box_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin_larger"
android:layout_marginBottom="#dimen/margin_larger"
android:textSize="#dimen/font_normal"
android:textColor="#color/font_black"
android:textStyle="italic"
android:text="Sample Text Here"
/>
</LinearLayout>
fragment_museum
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.bluecadet.android.nasm.ui.AtTheMuseumFragment"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="100dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:descendantFocusability="blocksDescendants"
>
<TextView
android:id="#+id/museum_header"
style="#style/header"
android:text="#string/museum_header"
android:layout_margin="#dimen/margin_larger"
android:elevation="8dp"
/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="275dp"
android:elevation="2dp"
>
<FrameLayout
android:id="#+id/museum_map"
android:layout_height="fill_parent"
android:layout_width="match_parent"
/>
<include
layout="#layout/view_explore_map" />
</FrameLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/stories_list_view"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/margin_normal"
android:layout_marginLeft="#dimen/margin_small"
android:layout_marginRight="#dimen/margin_small"
android:layout_marginTop="#dimen/margin_normal"
android:stretchMode="columnWidth"
/>
<Button
android:id="#+id/load_more"
style="#style/home_button"
android:gravity="center"
android:text="#string/button_load_more"
/>
</LinearLayout>
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
ViewTreeObserver code I'm playing with now. It's in Fragment.
mTopStoriesListView.setLayoutManager(new NewMeasuredStaggeredLayoutManager(2, StaggeredGridLayoutManager.VERTICAL, mTopStoriesListView));
mTopStoriesListView.setNestedScrollingEnabled(false);
//Testing Issue 54
final ViewTreeObserver viewTreeObserver = mTopStoriesListView.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mTopStoriesListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int l = 0,r = 0;
for(int i = 0 ; i < mNearMeAdapter.getItemCount(); i++){
int h = mTopStoriesListView.getLayoutManager().findViewByPosition(i).getHeight();
ViewGroup.MarginLayoutParams layout = (ViewGroup.MarginLayoutParams) mTopStoriesListView.getLayoutManager()
.findViewByPosition(i).getLayoutParams();
int t = layout.topMargin;
int b = layout.bottomMargin;
if(i % 2 == 0){
l += h + t + b;
}else{
r += h + t + b;
}
}
int viewHeight = (l > r) ? l : r;
mTopStoriesListView.getLayoutParams().height = viewHeight;
Log.d("TAG", String.valueOf(viewHeight));
}
});
}
//END TEST
Have you look at ViewTreeObserver ?
I got a similar problem on a passed project and I have found it more reliable than onMesure to dynamically get Layout properties
You can go through it from here : http://developer.android.com/reference/android/view/ViewTreeObserver.html

How can I start activity inside frame?

I'm trying to make a custom tabbar with scrolling tabbar items.
activity_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"
android:orientation="vertical"
android:background="#drawable/bg"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/main_tabbar"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_below="#+id/main_rlTopbar" >
<FrameLayout
android:id="#+id/main_tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:background="#drawable/bottombar" >
<LinearLayout
android:id="#+id/main_llTabs"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</RelativeLayout>
mainactivity.java
...
m_scrollTabbar = new HScrollTabbar(this, R.id.main_tabcontent, R.id.main_llTabs);
m_scrollTabbar.addTab(null, 0, HomeActivity.class, true);
...
hscrolltabbar.java
public class HScrollTabbar {
private int m_nTabContentId = -1;
private int m_nScrollTabbarId = -1;
private Activity m_activityParent = null;
private ArrayList<ButtonTabbarItem> m_aryTabButton = new ArrayList<ButtonTabbarItem>();
private int m_nSelectedIndex = -1;
public void addTab(String labelId, int drawableId, Class<?> c) {
LinearLayout llTabs = (LinearLayout) m_activityParent.findViewById(m_nScrollTabbarId);
ButtonTabbarItem item = new ButtonTabbarItem(m_activityParent, c, m_aryTabButton.size());
llTabs.addView(item);
m_aryTabButton.add(item);
if (m_aryTabButton.size() == 1) {
setSelectedIndex(0);
}
item.setOnSelectTabListener(onSelectTabListener);
}
private OnSelectTabListener onSelectTabListener = new OnSelectTabListener() {
#Override
public void onSelect(int nSelectedIndex) {
setSelectedIndex(nSelectedIndex);
}
};
public void setSelectedIndex(int nIndex) {
if (m_nSelectedIndex == nIndex)
return;
ButtonTabbarItem item = null;
if (m_nSelectedIndex > -1) {
item = m_aryTabButton.get(m_nSelectedIndex);
item.setSelected(false);
}
m_nSelectedIndex = nIndex;
item = m_aryTabButton.get(m_nSelectedIndex);
item.setSelected(true);
FrameLayout frame = (FrameLayout) m_activityParent.findViewById(m_nTabContentId);
Intent intent = new Intent();
intent.setClass(frame.getContext(), item.getClassTarget());
frame.getContext().startActivity(intent);
}
public int getSelectedIndex() {
return m_nSelectedIndex;
}
}
buttontabbaritem.java
public class ButtonTabbarItem extends FrameLayout {
private static final int TAB_BTN_TAG = 100;
private Class<?> m_classTarget;
OnSelectTabListener m_listener = null;
public ButtonTabbarItem(Context context, Class<?> classTarget, int nIndex) {
super(context);
LinearLayout layout = new LinearLayout(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.hscroll_tabbar_item, layout);
addView(view);
Button btn = (Button) view.findViewById(R.id.hscroll_tabbar_item_btn);
btn.setOnClickListener(onClickTab);
btn.setTag(TAB_BTN_TAG + nIndex);
m_classTarget = classTarget;
}
public Class<?> getClassTarget() {
return m_classTarget;
}
public void setClassTarget(Class<?> classTarget) {
m_classTarget = classTarget;
}
public void setSelected(boolean bSelected) {
if (bSelected) {
} else {
}
}
private OnClickListener onClickTab = new OnClickListener() {
#Override
public void onClick(View v) {
if (m_listener != null)
m_listener.onSelect((Integer) v.getTag() - TAB_BTN_TAG);
}
};
public interface OnSelectTabListener {
public void onSelect(int nSelectedIndex);
}
public void setOnSelectTabListener(OnSelectTabListener listener) {
m_listener = listener;
}
}
FrameLayout frame = (FrameLayout) m_activityParent.findViewById(m_nTabContentId);
Intent intent = new Intent();
intent.setClass(frame.getContext(), item.getClassTarget());
frame.getContext().startActivity(intent);
I'm trying to start activity inside frame, but it's not work.
Please help me.

Categories