How to add icon for child node? - android

I use this lib. I want add icon for any child. But i don't know how i can do it.please help me.thanks any body.i read sample but ..this is my code.please read link
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TreeNode root = TreeNode.root();
final TreeNode parent = new TreeNode("Melk");
final TreeNode child0 = new TreeNode("Build_1");
TreeNode child1 = new TreeNode("Build_2");
TreeNode child_1 = new TreeNode("Aparteman_1");
TreeNode child_3 = new TreeNode("Aparteman_2");
TreeNode child_4 = new TreeNode("Senfi_1");
TreeNode child_5 = new TreeNode("Senfi_2");
child_1.addChildren(child_4, child_5);
child0.addChildren(child_1, child_3);
parent.addChildren(child0, child1);
root.addChild(parent);
Button del = (Button) findViewById(R.id.del);
parent.setClickListener(new TreeNode.TreeNodeClickListener() {
#Override
public void onClick(TreeNode node, Object value) {
Toast.makeText(getApplicationContext(),"",Toast.LENGTH_LONG).show();
}
});
LinearLayout containerView = (LinearLayout) findViewById(R.id.m);
AndroidTreeView tView = new AndroidTreeView(getApplicationContext(), root);
containerView.addView(tView.getView());
}
}
post edited.i need your help.

You have to use custom adapter as it use for default android listview only difference is to extend TreeNode.BaseNodeViewHolder and overwrite createNodeView
this is a structure
public class MyHolder extends TreeNode.BaseNodeViewHolder<IconTreeItem> {
...
#Override
public View createNodeView(TreeNode node, IconTreeItem value) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.layout_profile_node, null, false);
TextView tvValue = (TextView) view.findViewById(R.id.node_value);
tvValue.setText(value.text);
return view;
}
public static class IconTreeItem {
public int icon;
public String text;
}
}
for more information this tutorial will help you on how use custom adapter
https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView

Related

Struggling to replace SPINNER with BUTTONS populated from database

Trying to replace spinner with buttons dynamically populated from database.
Normally spinner use array adapter and built-in List Item Layouts "android.R.layout.simple_spinner_item"etc.
How should it be modified if instead of spinner you want to populate buttons?
Should I replace layouts for spinner in my in loadDifficulties() method with layouts for buttons?
HERE HOW IT WORKED WITH SPINNER
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_screen);
spinnerDifficulty = findViewById(R.id.spinner_quizlist);
loadDifficulties();
Button startTest = findViewById(R.id.start_test);
startTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startQuiz();
}
});
}
private void startQuiz() {
ListQuiz selectedLevel = (ListQuiz) spinnerDifficulty.getSelectedItem();
int LevelListID = selectedLevel.getId();
String quizListName = selectedLevel.getName();
Intent intent = new Intent(StartingScreenActivity.this, MainActivity.class);
intent.putExtra(EXTRA_DIFFICULTY_ID, LevelListID);
intent.putExtra(EXTRA_DIFFICULTY_NAME, quizListName);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
private void loadDifficulties(){
QuizDbHelper dbHelper = QuizDbHelper.getInstance(this);
List<ListQuiz> LevelList = dbHelper.getAllListQuiz();
ArrayAdapter<ListQuiz> adapterLevelList = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, LevelList); adapterLevelList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDifficulty.setAdapter(adapterLevelList);
}
onCreate(){
LinearLayout listOrders = findViewById(R.id.listOrders);
for (int i = 0; i < listForShowing.size(); i++){
String text = listForShowing.get(i);
listOrders.addView(createButton(text));
}
listOrders.requestLayout();
}
public Button createButton(String text){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Button button = inflater.inflate(R.layout.button, null);
button.setText(text);
}
Briefly
Created LinearLayout for buttons.
I didn't need to use ArrayAdapter in the loadDifficulties anymore.
Added all needed parameters to startQuiz() (in my case int & String) simplifying method to Intents only.
private ArrayAdapter <ListQuiz> adapter;
private Button autobutton;
public int categorySize;
private List<ListQuiz> categoryName;
private LinearLayout QuizListLayout;
private Button levelButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_screen);
autobutton = findViewById(R.id.autobutton);
loadDifficulties();
QuizListLayout = findViewById(R.id.layoutForButtons);
for(int i=0; i<categorySize;i++){
levelButton =new Button(this);
levelButton.setText("" + categoryName.get(i));
levelButton.setId(i);
final int index = i;
levelButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
levelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startQuiz(v.getId(), categoryName.get(index).toString());
}
});
QuizListLayout.addView(levelButton);
}
}
private void startQuiz(int LevelListID, String quizListName) {
Intent intent = new Intent(StartingScreenActivity.this, MainActivity.class);
intent.putExtra(EXTRA_DIFFICULTY_ID, LevelListID);
intent.putExtra(EXTRA_DIFFICULTY_NAME, quizListName);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
private void loadDifficulties(){
QuizDbHelper dbHelper = QuizDbHelper.getInstance(this);
List<ListQuiz> LevelList = dbHelper.getAllListQuiz();
categorySize = dbHelper.getAllListQuiz().size();
categoryName = dbHelper.getAllListQuiz();
buttonlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/layoutForButtons">
</LinearLayout>

How to create a RecyclerView of Buttons

I am creating an AlertDialog custom class, called ActionDialog, which will contains a RecyclerView containing Buttons. I have a List of Button that I populate in the custom class ActionDialog (for now i just populate with useless Button just to try to use it, except one which I create in another class).
The problem is that when i create the AlertDialog, all buttons are showing empty, they are showed but with no text/no clicklistener (as you can see in the image below).
(I have added a custom ActionListener to a Button in another class and then give it as parameter in ActionDialog class. Will it lose the ActionListener?)
Here is the result.
I will leave here my ActionDialog class code, and the adapter class.
This is ActionDialog class:
public class ActionDialog extends AlertDialog{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private Button actionButtons;
private List<Button> buttons;
private Activity context;
public ActionDialog(#NonNull Activity context, Button actionButtons) {
super(context);
this.context = context;
this.actionButtons = actionButtons;
buttons = new ArrayList<>();
initButton();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
}
private void initButton(){
initZoneButton();
//TODO init all buttons
Button b1 = new Button(context);
b1.setText("ExampleButton1");
Button b2 = new Button(context);
b2.setText("ExampleButton2");
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String a;
}
});
buttons.add(b1);
buttons.add(b2);
}
private void initZoneButton(){
buttons.add(actionButtons); //this button is created in another class and give as parameter in this class
}
public void createDialog(){
Builder mBuilder = new Builder(context);
View view = context.getLayoutInflater().inflate(R.layout.dialog_actionbuttons_layout, null);
mRecyclerView = view.findViewById(R.id.dialog_actionbuttons_rv);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ActionButtonsAdapter(buttons);
mRecyclerView.setAdapter(mAdapter);
mBuilder.setView(view);
mBuilder.create().show();
}
}
Here is the RecyclerView adapter class:
public class ActionButtonsAdapter extends RecyclerView.Adapter<ActionButtonsAdapter.ViewHolder>{
private List<Button> dataButtons;
static class ViewHolder extends RecyclerView.ViewHolder {
Button actionButton;
ViewHolder(View v) {
super(v);
actionButton = v.findViewById(R.id.action_button_rv);
}
}
public ActionButtonsAdapter(List<Button> dataButtons){
this.dataButtons = dataButtons;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.actionButton = dataButtons.get(position);
//i think the problem is here, maybe
}
#Override
public ActionButtonsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_actionbutton_layout, parent, false);
return new ViewHolder(v);
}
#Override
public int getItemCount() {
return dataButtons.size();
}
}
I think in the onBindViewHolder method you should do what ever you want to do with your button.
Also there is no need for the list of buttons here. Make a list the data you need to be held in the Buttons RecyclerView.
I have a RecyclerView that will display Genres for restaurants lets say, So I will create a List of strings to hold these genres names (chickens, meats, etc,..)
Setting its text
holder.actionButton.setText(// Make use of position here);
Or Click Listeners.
Update
You can check google samples for recyclerview here
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Log.d(TAG, "Element " + position + " set.");
// Get element from your dataset at this position and replace the contents of the view
// with that element
viewHolder.getTextView().setText(mDataSet[position]);
}
wheres mDataset is Array of Strings.

RecyclerView OnClick Event Does Not Work

I got some trouble while setting an onclicklistener to my recyclerview. I saw that similar question has been asked, I tryed all the ways I can find but I got no result. Here is how I implement it:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Question> values;
private Context context;
public class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener{
public TextView txtHeader;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
txtHeader = (TextView) v.findViewById(R.id.header);
}
#Override
public void onClick(View view) {
Log.d("Tag:", "Here");
int position = getLayoutPosition();
String question = values.get(position).getQuestion();
String choiceA = values.get(position).getChoiceA();
String choiceB = values.get(position).getChoiceB();
String choiceC = values.get(position).getChoiceC();
Integer questionID = values.get(position).getQuestionID();
Intent intent = new Intent(context,SingleQuestionActivity.class);
intent.putExtra("question", question);
intent.putExtra("choiceA", choiceA);
intent.putExtra("choiceB", choiceB);
intent.putExtra("choiceC", choiceC);
intent.putExtra("questionID", questionID);
QuestionActivity questionActivity =
(QuestionActivity) context;
questionActivity.goToSingleQuestionScreen(intent);
}
}
...
As you can see I put an Log.d to see if it comes to onClick method it did not. And I set this adapter in my QuestionActivity class like below:
public class QuestionActivity extends AppCompatActivity{
...
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
initializeComponents();
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setBackgroundColor(Color.YELLOW);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
QuestionRepository questionRepository =
QuestionRepository.getInstance(getApplicationContext());
Intent intent = getIntent();
questions = questionRepository
.getCategorizedQuestions(intent.getIntExtra("category", 1));
mAdapter = new MyAdapter(questions, this);
recyclerView.setAdapter(mAdapter);
...
Where am I doing wrong?
Try :
public ViewHolder(View v) {
super(v);
layout = v;
txtHeader = (TextView) v.findViewById(R.id.header);
v.setOnClickListener(this);
}
Hope this helps
This can be easily and cleanly done using Butterknife.
Add to your gradle file dependencies and sync project.
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
Now it is easier to set listeners and bind views. You could do the following:
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.header)
TextView header;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
#OnClick
void onClick(View view) {
Log.d("pos", getAdapterPosition());
Intent intent ...
...
view.getContext().startActivity(intent);
}
}
By using #BindView annotation you don't have to call findViewById()every time - Butterknife does that for you. Also you don't have to implement listeners - just add #OnClick annotation.
Also there is no need to get QuestionActivity and call its method from adapter (which I assume is starting another activity). Context can be obtained from view.getContext() as every view holds a reference to context and then you can call e.g. startActivity(intent)
For further reading I recommend
https://medium.com/#pranaypatel/butterknife-a-viewbinding-library-for-android-beginner-guide-fd92caf8e505
http://www.vogella.com/tutorials/AndroidButterknife/article.html

Custom Spinner Crashing

I asked a question on here about a week or so ago about a custom spinner and got led to this guide. http://app-solut.com/blog/2011/03/using-custom-layouts-for-spinner-or-listview-entries-in-android/
I followed it and I've tried adapting it to work with my code and pull the results from a database onto the spinner but it keeps crashing.
This is the code for the spinner.
public class EditTeam extends Activity {
private final List<SpinnerEntry> spinnerContent = new LinkedList<SpinnerEntry>();
private Spinner D1Spinner;
private final ETSpinnerAdapter D1Adapter = new ETSpinnerAdapter(spinnerContent, this);
DataBaseHelper myDbHelper = new DataBaseHelper(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editteam);
myDbHelper = new DataBaseHelper(this);
myDbHelper.openDataBase();
fillSpinner();
}
private void fillSpinner() {
Cursor c = myDbHelper.FetchDrivers();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{"FirstName", "LastName"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
spinnerContent.add(new SpinnerEntry(1, null, "Test"));
//adapter.setDropDownViewResource( R.layout.spinner_entry_with_icon );
D1Spinner = (Spinner) findViewById(R.id.spr_Driver1);
D1Spinner.setAdapter((SpinnerAdapter) D1Adapter);
}
}
And I am using the two classes from that contacts example which are un-modified at the moment.
As you can see I'm trying to just manually add one item at the moment but it just crashes when you load it.
This seems to be the breaking point?
05-25 15:17:34.773: E/AndroidRuntime(241): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.f1manager.android/com.f1manager.android.EditTeam}: java.lang.ClassCastException: com.f1manager.android.ETSpinnerAdapter
Any ideas would be great.
Thanks.
ETSpinnerAdapter Code (Unmodified from the original code in the example):
public class ETSpinnerAdapter {
private final List<SpinnerEntry> content;
private final Activity activity;
public ETSpinnerAdapter(List<SpinnerEntry> content, Activity activity) {
super();
this.content = content;
this.activity = activity;
}
public int getCount() {
return content.size();
}
public SpinnerEntry getItem(int position) {
return content.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final LayoutInflater inflater = activity.getLayoutInflater();
final View spinnerEntry = inflater.inflate(
R.layout.spinner_entry_with_icon, null); // initialize the layout from xml
final TextView contactName = (TextView) spinnerEntry
.findViewById(R.id.spinnerEntryContactName);
final ImageView contactImage = (ImageView) spinnerEntry
.findViewById(R.id.spinnerEntryContactPhoto);
final SpinnerEntry currentEntry = content.get(position);
contactName.setText(currentEntry.getContactName());
//contactImage.setImageBitmap(currentEntry.getContactPhoto());
return spinnerEntry;
}
}
It would seem like your ETSpinnerAdapter is not a SpinnerAdapter as your are getting a class cast exceptin. Maybe you can post your code for the ETSpinnerAdapter?

Using Intent with actions

Right. I have an action that needs to call another activity. As I understand this, I need to use Intents to do so if I want to parse values to this activity.
However, my code fails and im a little lost as to why.
My main activity:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
/*Menu item: String name, String menu ID*/
/*ToDo: Logic to fecth new menu structure from server*/
menuItem MI1 = new menuItem("menu item 1","1");
menuItem MI2 = new menuItem("menu item 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new menuAdapter(this, AMI));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
//Toast.makeText(Runner.this, AMI.get(position).getMenuID(), Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(v.getContext(), showMenu.class);
myIntent.putExtra("parentID", AMI.get(position).getMenuID());
startActivityForResult(myIntent, 0);
}
});
The "Toast" works just fine, however when I call the showMenu class it crashes.
The showMenu class looks as follows:
public class showMenu extends Activity{
public String menuParent = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.submenu);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
menuParent = extras.getString("parentID");
}
/*ToDo: Logic to fecth new menu structure from server*/
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
menuItem MI1 = new menuItem("submenu 1","1");
menuItem MI2 = new menuItem("submenu 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new subMenuAdapter(this, AMI));
}
public class subMenuAdapter extends BaseAdapter {
private ArrayList<menuItem> MIL = new ArrayList<menuItem>();
public static final int ACTIVITY_CREATE = 10;
public subMenuAdapter(Context c, ArrayList<menuItem> AMI) {
MIL = AMI;
}
public int getCount() {
return MIL.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
v = (LinearLayout) li.inflate(R.layout.grid_item, null);
TextView tv = (TextView)v.findViewById(R.id.grid_text);
tv.setText(MIL.get(position).getMenuname());
} else {
v = convertView;
}
return v;
}
}
}
Any idea why it crashes?
I think you have to register your Intent in your AndroidManifest.xml
<activity
android:name="Package.Name.showMenu"
android:theme="#android:style/Theme.Light"></activity>
As both activities are from same application, there are some other ways as well to pass data between instead of intents. check the link below:
http://developer.android.com/resources/faq/framework.html#3
If you want to use only intents, can you please specify the error you are facing, so that someone can reply you correctly.
if you want to parse values to another activity,you must use startActivityForResult.This is called sub_activity.

Categories

Resources